When I compile this with Rust 1.3, the compiler tells me that virtual
structs have been removed from the language:
struct Foo: Bar { }
In Rust, there is no concept of "inheriting" the properties of a struct. Instead, when you are designing the relationship between objects do it in a way that one's functionality is defined by an interface (a trait in Rust).
There is no struct inheritance in Rust. Instead we use composition and include an instance of Foo in Bar (since the field is a value, it is stored inline, so if there were fields, they would have the same layout in memory as the Java version (probably, you should use #[repr(C)] if you want to be sure)).
Rust doesn't support inheritance.
A struct is a user-defined data type that contains fields which define its particular instance. Structs help programmers implement abstract ideas in a more understandable fashion. For example, creating a Student struct that consists of an id , name , marks , etc. makes the code more readable.
Short answer, you can't do inheritance with structs.
Instead of inheritance, Rust uses composition. However, you can do inheritance within traits. Traits don't have data, but they can define functions, so you can many of the benefits of inheritance by using them:
trait Foo { fn foo(&self); } trait FooBar: Foo { fn foobar(&self); }
An implementor of FooBar
must implement foo
(unless you provide a default implementation).
One way Rust does specialization is typically through enums
, which are very powerful in Rust. One of the Rust developers wrote a good blog series about how Rust approaches these types of problems. I recommend reading through it as well as reading through the official 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