Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a type hierarchy using Rust enumerations?

Tags:

rust

I'm trying to make a compiler in Rust, but I'm having problems understanding how to define a type hierarchy using enumerations. We have for example:

enum Thing {
    Animal,
    Plant,
}

struct Plant {
    color: String,
}

enum Animal {
    Dog,
    Cat,
}

struct Cat {
    name: String,
}

struct Dog {
    name: String,
}

let x = Dog { name: john };

If I do pattern matching, will Dog be considered of Animal type (or Thing type)? How do I create this type hierarchy using enums and structs? My type hierarchy has many levels of depth.

like image 230
André Luiz Avatar asked Sep 18 '25 19:09

André Luiz


1 Answers

When you look at this piece of code:

enum Thing {
    Animal,
    Plant,
}

struct Plant {
    color: String,
}

You see the word Plant twice. The important thing to note is that the two Plants are different, unrelated things. Just because they have the same name doesn't mean that they represent the same thing, and in fact they don't really have the same name when you take the fully qualified name: the first one is ::Thing::Plant and the second one is just plain ::Plant.

If you want to link the two, you will need to make it explicit with:

enum Thing {
    Animal(Animal),
    Plant(Plant),
}

For more details, you can look at the IpAddr example in the Rust book.

like image 145
Jmb Avatar answered Sep 23 '25 07:09

Jmb