Generic Box<Trait> and Trait in struct

Hello.

I have a question about language features.

I'm particularly interested in dereferencing for Box.
Is it possible to write a generalized structure that can store "an object that implements trait" or Box< an object that implements trait>. Example below:

trait Say
{
	fn say(&self);
}

struct Dog
{}

struct Human
{}

impl Say for Dog
{
	fn say(&self)
	{
		println!("Woof!");
	}
}

impl Say for Human
{
	fn say(&self)
	{
		println!("Hello!");
	}
}

struct House<S>
where S: Say
{
	s: S
}

impl<S> House<S>
where S: Say
{
	fn new(s: S)->House<S>
	{
		House{s}
	}

	fn habitant_say(&self)
	{
		self.s.say();
	}
}

fn main() {
	
	let dog=Dog{};

	let h=House::new(dog);

	//let dog_in_box=Box::new(dog);

	//let h=House::new(dog_in_box);

	h.habitant_say();
}

What do I need to change so that I can create House< Dog>, House< Human> .... as well as House<Box< Dog>>, House<Box< Human>> ....
Or is it impossible?

Add this impl

impl<S: ?Sized + Say> Say for Box<S> {
    fn say(&self) {
        S::say(self)
    }
}
1 Like

Cool!!!

That step was fundamental :stuck_out_tongue:

1 Like

Because I studied from a very strange book. The disgusting method of submitting knowledge from the author.

"Blandy Jim, Orendorff Jason. Programming Rust: Fast, Safe Systems Development".

PS: Sorry for my english. This is not my main language.

Is that a pun?

:grin:

1 Like