首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >__rust_force_expr到底是做什么的?

__rust_force_expr到底是做什么的?
EN

Stack Overflow用户
提问于 2021-12-18 10:09:16
回答 1查看 411关注 0票数 7

我查看了Rust中的vec![]宏实现,并注意到它使用了__rust_force_expr!宏。这就是后者的执行情况:

代码语言:javascript
复制
/// 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
    };
}

有人能更清楚地了解它的确切作用吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-18 13:05:02

它对宏的使用方式没有任何结果,它只会通过告诉编译器宏的输出总是一个表达式,而不是一个项或多个表达式来提高错误消息的质量。

添加用于改进的特定错误是在模式匹配中使用vec![],这是无效的(不能在结构上匹配Vec):

代码语言:javascript
复制
let x: Option<Vec<i32>> = Some(vec![]);
match x {
    Some(my_vec![]) => println!("1"),
    _ => println!("2"),
};

结果:

代码语言:javascript
复制
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,我们得到了一个更好的错误:

代码语言:javascript
复制
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![]生成一个表达式,并且没有对宏后面的函数调用的引用。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70402502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档