Question

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?

Was it helpful?

Solution

impl CanGreet for Person {
    fn greet(&self) {
        self.has_name.greet()
    }
}

Then you can just person.greet().

Licensed under: CC-BY-SA with attribution
scroll top