Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to inherit a struct in Rust 1.3?

Tags:

When I compile this with Rust 1.3, the compiler tells me that virtual structs have been removed from the language:

struct Foo: Bar {  } 
like image 756
bitnick Avatar asked Sep 23 '15 09:09

bitnick


People also ask

Why Rust does not support inheritance?

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).

Is there inheritance 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)).

Does Rust support multiple inheritance?

Rust doesn't support inheritance.

What is a struct Rust?

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.


1 Answers

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.

like image 56
beatgammit Avatar answered Oct 02 '22 20:10

beatgammit