About impl dyn Trait

What is the semantic of A ? It seems it is not a default implementation.

trait Trait {
    fn demo(&self);
}
struct S;
impl dyn Trait {         // A
    fn demo(&self) {}
}
//impl Trait for S {}
fn main() {
    let a = S;
    //a.demo();
}

To define a default implementation, put it in the trait definition directly:

trait Trait {
    fn demo(&self) { /* ... */ }
}

dyn Trait is a builtin Rust type used for dynamic dispatch, so the impl dyn Trait is defining inherent methods for dyn Trait objects, the same way that impl S defines them for the type S-- The methods defined here can only be called on a dyn Trait object. This can occasionally be useful to provide an alternative implementation of trait methods that require Self: Sized :

trait Trait {
    fn demo(&self)->Self where Self: Sized { unimplemented!() }
}

impl dyn Trait {
    fn dyn_demo(&self)->Box<dyn Trait> { unimplemented!() }
}

aha , got it , it is a bonus for Trait Object

trait Trait {
    fn demo(&self) {println!("static");}
}

struct S;

impl dyn Trait {
    fn demo2(&self) {println!("dyn");}
}
impl Trait for S {}
fn main() {
    let a = S;
    a.demo();
    //a.demo2();     
    let b : &dyn Trait = &S;
    b.demo();
    b.demo2();
}

The thing to understand here is that dyn Trait is a specific separate type from e.g. the struct S. It's just that a &S can be converted to an &dyn Trait.

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.