为什么我的特质定义与2015版本编译而不是与2018版本编译?

T.S*_*hin 8 rust rust-2018

我写了这个简单的程序:

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

fn main() {                                                                                                             
    let x = 0;                                                                                                          
}    
Run Code Online (Sandbox Code Playgroud)

我编译了这个rustc --edition=2018 main.rs并收到错误消息:

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

编译通过rustc --edition=2015 main.rsrustc main.rs不会导致此错误,尽管有一些警告.

这段代码有什么问题?

And*_*kin 9

2018年版中删除了匿名特征参数:不再有匿名特征参数.

如果要忽略参数,请_:在之前添加&mut T:

trait Command<T> {
    fn execute(&self, _: &mut T);
}
Run Code Online (Sandbox Code Playgroud)

使用rustc main.rs作品进行编译,因为它默认为--edition=2015.


实际上,如果您将自己main.rs置于一个新的Cargo项目中,那么请edition = "2018"从中移除Cargo.toml并运行

cargo fix --edition
Run Code Online (Sandbox Code Playgroud)

然后Cargo将_:自动添加缺失.请参阅将现有项目转换为新版本.