这并不影响宏的使用方式,它只是用于在宏被错误使用时改善错误消息的质量,向编译器表明宏的输出始终是一个表达式,而不是一个项或多个表达式。
此更改旨在改善在模式匹配中使用vec![]
(无效的操作,您无法对Vec
进行结构匹配)时产生的特定错误:
let x: Option<Vec<i32>> = Some(vec![]);
match x {
Some(my_vec![]) => println!("1"),
_ => println!("2"),
};
导致/造成
error[E0164]: expected tuple struct or tuple variant, found associated function `Vec::new`
--> src/main.rs:9:9
|
9 | Vec::new()
| ^^^^^^^^^^ `fn` calls are not allowed in patterns
...
15 | Some(my_vec![]) => println!("1"),
| --------- in this macro invocation
|
= help: for more information, visit https://doc.rust-lang.org/book/ch18-00-patterns.html
= note: this error originates in the macro `mvec` (in Nightly builds, run with -Z macro-backtrace for more info)
这是一个相当令人困惑的错误,特别是在使用vec![1,2,3]
语法时。看起来调用者中没有任何函数调用,但是通过将vec!
的主体用__rust_force_expr
包装,我们可以得到更好的错误提示:
error: arbitrary expressions aren't allowed in patterns
--> src/main.rs:15:10
|
15 | Some(vec![]) => println!("1"),
| ^^^^^^
|
= note: this error originates in the macro `vec` (in Nightly builds, run with -Z macro-backtrace for more info)
这样就更加清晰易懂了:
vec![]
生成了一个表达式,其中没有任何宏后面的函数调用引用。