Impl trait for dyn does not implement: what am I missing?

I have two traits. I would like all traits that implement one to also implement the other. The syntax for doing this (I believe) was impl SomeTrait for dyn OtherTrait: Here is an example that does not compile with a playground link. I do not understand why PrintString is not automatically implemented for Thing when it does implement MakeString

pub trait PrintString {
    fn print_string(&self, s: &str) {
        println!("You entered {}!", s);
    }
}

pub trait MakeString {
    fn make_string(&self) -> String;
}


impl PrintString for dyn MakeString {}

pub struct Thing;

impl MakeString for Thing {
    fn make_string(&self) -> String {
        "I am a thing!".to_string()
    }
}

fn main() {
    let thing = Thing{};
    let _ = thing.make_string(); // See! MakeString is implemented!
    thing.print_string(); // error[E0599]: no method named `print_string` found for struct `Thing` in the current scope
    println!("");
}

dyn MakeString is a specific type. Thing is a different type.

The correct syntax for what you want is:

impl<T: MakeString> PrintString for T {}
2 Likes

Pedantically, if you want to be as general as possible, it should be

impl<T: ?Sized + MakeString> PrintString for T {}

Without the ?Sized bound, you won't actually implement PrintString for unsized types like dyn MakeString itself.

4 Likes

Perfect- thanks much for the quick reply.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.