Is it Rusty? These are posts chronicling my journey learning Rust. At this point I'm uncertain whether what I'm doing is actually the recommended way of doing things.
Given two structs with common fields, I was wondering how I could go about creating a "base" struct so that those fields could be shared. For example, if we had the following two structs, how would we share the name
field?
In OOP I'd create a base class which contains that property. However, as far as I can tell, in Rust, there is no notion of inheritance of fields. A solution is to have a third struct which defines the common fields, and an extra field which holds the value of the "child" struct.
// highlight-start
// highlight-end
These can be used like this:
Cool. But we can add anything we like into Pet::animal
, including a Car
. To solve this you can implement a trait to restrict the types that can be set on animal
.
// highlight-start
// highlight-end
// highlight-start
// highlight-start
// highlight-end
// highlight-start
// highlight-end
Now by restricting what can be used in the animal
field, the previous fn main {
code will no longer work:
Try it out in the playground.