我查看了Rust中的vec![]宏实现,并注意到它使用了__rust_force_expr!宏。这就是后者的执行情况:
/// Force AST node to an expression to improve diagnostics in pattern position.
#[doc(hidden)]
#[macro_export]
#[unstable(feature = "liballoc_internals", issue = "none", reason = "implementation detail")]
macro_rules! __rust_force_expr {
($e:expr) => {
$e
};
}有人能更清楚地了解它的确切作用吗?
发布于 2021-12-18 13:05:02
它对宏的使用方式没有任何结果,它只会通过告诉编译器宏的输出总是一个表达式,而不是一个项或多个表达式来提高错误消息的质量。
添加用于改进的特定错误是在模式匹配中使用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![]生成一个表达式,并且没有对宏后面的函数调用的引用。
https://stackoverflow.com/questions/70402502
复制相似问题