【发布时间】:2021-10-04 12:07:13
【问题描述】:
我在我的代码中看到了以下行,但我不确定它的作用,因为我之前没有遇到过 @ 运算符。
if let e@Err(_) = changed {
...
}
如果没有@ 运算符,这行代码可以写吗?会是什么样子?
【问题讨论】:
标签: rust
我在我的代码中看到了以下行,但我不确定它的作用,因为我之前没有遇到过 @ 运算符。
if let e@Err(_) = changed {
...
}
如果没有@ 运算符,这行代码可以写吗?会是什么样子?
【问题讨论】:
标签: rust
这是一个way to bind the matched value of a pattern to a variable(使用语法:variable @ subpattern)。例如,
let x = 2;
match x {
e @ 1 ..= 5 => println!("got a range element {}", e),
_ => println!("anything"),
}
【讨论】:
if let Err(e) = changed 不同于 (B) if let e@Err(_) = changed?
@ 绑定 匹配值,它将是 Result(假设 changed 是 Result)类型。所以e的类型在第二种情况下(B)是changed的类型
【讨论】:
回答你的第二个问题,是的,看起来像
if let Err(_) = &changed {
// continue to use `changed` like you would use `e`
}
请注意,为了在正文中继续使用changed,您需要匹配引用&changed。否则它将被移动并丢弃(除非它恰好是Copy)。
【讨论】:
if let Err(_) = changed 永远不会移动 changed,因为左侧没有可以移动的目标。 (Example)
if changed.is_err()。
if changed.is_err() { let e = changed; ...}