问题描述
ref
不能做什么引用?可以
What can ref
do that references couldn't? Could
match value.try_thing() {
&Some(ref e) => do_stuff(e),
// ...
}
不能等同地表达为
match value.try_thing() {
&Some(e) => do_stuff(&e),
// ...
}
推荐答案
否,建议的语法无法避免.您的语法不允许引用,否则将允许移动.在此示例中, inner
是 val
中整数的副本,对其进行更改不会影响 val
:
No, it is not avoidable with your proposed syntax. Your syntax does not allow for taking a reference when otherwise a move would be permissable. In this example, inner
is a copy of the integer from val
and changing it has no effect on val
:
fn main() {
let mut val = Some(42);
if let &mut Some(mut inner) = &mut val {
inner += 1;
}
println!("{:?}", val); // Some(42)
}
需要 ref
关键字来强制引用:
The ref
keyword is needed to force taking a reference:
fn main() {
let mut val = Some(42);
if let &mut Some(ref mut inner) = &mut val {
*inner += 1;
}
println!("{:?}", val); // Some(43)
}
匹配人体工程学允许以更简单的方式编写代码:
Match ergonomics allows writing this in a simpler manner:
fn main() {
let mut val = Some(42);
if let Some(inner) = &mut val {
*inner += 1;
}
println!("{:?}", val);
}
但是,如果我们仅以这种语法开头,那么我们可能会遇到相反的问题和关键字,一个是强制移动.也许 Some(向内移动)
.在那个替代的宇宙中,会有一个问题问 move
关键字是否可以避免.
However, if we started with only this syntax, then we'd probably have the opposite problem and keyword, one to force a move instead; perhaps Some(move inner)
. In that alternate universe, there'd be a question asking if the move
keyword was avoidable.
另请参阅:
- 在采用& self或& mut self的函数中进行模式匹配时,如何避免使用ref关键字?
- Rust模式匹配如何确定绑定变量是引用还是值?
- 为什么在模式匹配中使用ref而不是星号?
- 引用枚举时要匹配的语法是什么?
- 举例":引用模式
这篇关于ref不能做什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!