Search code examples
rustrust-2018

Why does my trait definition compile with the 2015 edition but not with the 2018 edition?


I wrote this simple program:

trait Command<T> {                                                                                                      
    fn execute(&self, &mut T);                                                                                          
}                                                                                                                       

fn main() {                                                                                                             
    let x = 0;                                                                                                          
}    

I compiled this with rustc --edition=2018 main.rs and get the error message:

error: expected one of `:` or `@`, found `)`
 --> main.rs:2:29
  |
2 |     fn execute(&self, &mut T);
  |                             ^ expected one of `:` or `@` here

Compiling via rustc --edition=2015 main.rs or rustc main.rs doesn't cause this error, although there are some warnings.

What's the problem with this code?


Solution

  • Anonymous trait parameters have been removed in 2018 edition: No more anonymous trait parameters.

    Add _: before &mut T if you want to ignore the parameter:

    trait Command<T> {
        fn execute(&self, _: &mut T);
    }
    

    Compiling with rustc main.rs works, because it defaults to --edition=2015.


    Indeed, if you put your main.rs in a new Cargo project, then remove edition = "2018" from Cargo.toml, and run

    cargo fix --edition
    

    then Cargo will add the missing _: automatically. See Transitioning an existing project to a new edition.