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.
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 Plant
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With