Rust and composition [closed]
https://softwareengineering.stackexchange.com/questions/347871
-
11-01-2021 - |
سؤال
I have a piece of code.
struct HasName {
name: &'static str
}
trait CanGreet {
fn greet(&self);
}
impl CanGreet for HasName {
fn greet(&self) {
println!("Hello {}", self.name);
}
}
struct Person {
has_name: HasName
}
fn main() {
let person = Person {
has_name: HasName {
name: "Tristan"
}
};
person.has_name.greet();
}
It prints in the console the name of the person.
Although, my Rust implementation does not seem natural. I heard about Defer
, but it does not look like a great idea.
How do you work with composition in Rust?
المحلول
impl CanGreet for Person {
fn greet(&self) {
self.has_name.greet()
}
}
Then you can just person.greet()
.
لا تنتمي إلى softwareengineering.stackexchange