Rust supports composition of types through a feature called “trait inheritance”. This is similar to struct embedding in other languages, but with some key differences. Let’s explore how this works in Rust.
To run the program:
In this Rust example, we’ve demonstrated how to achieve similar functionality to struct embedding using composition and trait implementation. Rust’s approach provides more explicit control over the structure and behavior of types, while still allowing for flexible composition of functionality.
The Container struct contains a Base as a field, rather than embedding it directly. To access the num field or call the describe method of Base, we need to go through the base field of Container.
We’ve also shown how to implement a trait (Describer) for Container, which allows us to use Container wherever a Describer is expected. This is similar to how embedding in other languages can automatically implement interfaces.
Rust’s approach to composition and interfaces (traits) provides strong type safety and explicit control, while still allowing for flexible and reusable code structures.