2

Traits in Rust allow default implementation for trait methods: you can write some implementation right inside trait MyTrait {...} and it will be used in impl MyTrait for MyStruct later.

However, you can also write plain impl MyTrait, which does not appear to change program's behaviour:

trait MyTrait {
    fn foo(&self) {  // Default implementation
        println!("1");
    }
}

impl MyTrait for i32 {
}

fn main() {
    1i32.foo();  // Prints '1'
}

impl MyTrait {  // What is this?
    fn foo(&self) {
        println!("2");  // Does nothing?
    }
}

What is that impl MyTrait without any for SomeType? It compiles with only "dead code" warning, so I suppose it has some meaning for the compiler. But I don't understand if there is a way to call it.

yeputons
  • 8,478
  • 34
  • 67
  • 3
    tl;dr - `impl MyTrait {...}` is the old way of writing `impl dyn MyTrait {...}` and is how you add inherent methods to trait objects of `MyTrait`. See also [What makes something a "trait object"?](https://stackoverflow.com/questions/27567849/what-makes-something-a-trait-object) – trent Jan 01 '19 at 16:51
  • Note that it's [currently impossible to disambiguate](https://github.com/rust-lang/rust/issues/51402) between the two `foo` calls you have, even though both exist and are distinct. – Shepmaster Jan 01 '19 at 19:01

0 Answers0