What does 'impl MyTrait' do without 'for MyStruct' in Rust?

69 views Asked by At

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.

0

There are 0 answers