问题描述
我了解 &
的工作原理,但它与 ref
有什么区别?它们可以互换吗?
I understand how &
works, but what is the difference between that and ref
? Are they interchangeable?
我找到的唯一信息(因为在 Google 上搜索符号效果不佳)是 此页面Rust By Example,但它没有解释两者之间的区别.本书的信息量不大,ref
只是模式 一章中列出.但似乎 ref
也在该上下文之外使用.
The only information I found (because searching for symbols on Google doesn't work very well) is this page on Rust By Example, but it doesn't explain the difference between the two. The Book is not very informative, and ref
is only listed on the Patterns chapter. But it seems that ref
is used outside that context too.
那么,ref
有什么用,和&
有什么区别?
So, what are the uses of ref
, and what's the difference to &
?
推荐答案
ref
在模式中用于将引用绑定到 lvalue(左值是您可以取地址,或多或少).
ref
is used in patterns to bind a reference to an lvalue (an lvalue is a value you can take the address of, more or less).
理解模式与普通表达式倒退"很重要,因为它们习惯于解构值.
It's important to understand that patterns go "backwards" from normal expressions, since they're used to deconstruct values.
这是一个简单的例子.假设我们有这个:
Here's a simple example. Suppose we have this:
let value = 42;
我们可以通过两种方式绑定对 value
的引用:
We can bind a reference to value
in two ways:
let reference1 = &value;
let ref reference2 = value;
在第一种情况下,我们使用 &
作为运算符来获取 value
的地址.在第二种情况下,我们使用 ref
模式来解构"一个左值.在这两种情况下,变量的类型都是 &i32
.
In the first case, we use &
as an operator to take the address of value
. In the second case, we use the ref
pattern to "deconstruct" an lvalue. In both cases, the type of the variable is &i32
.
&
也可以用在模式中,但它的作用正好相反:它通过取消引用来解构引用.假设我们有:
&
can also be used in patterns, but it does the opposite: it deconstructs a reference by dereferencing it. Suppose we have:
let value = 42;
let reference = &value;
我们可以通过两种方式取消引用reference
:
We can dereference reference
in two ways:
let deref1 = *reference;
let &deref2 = reference;
这里deref1
和deref2
的类型都是i32
.
然而,并不总是可以用此处所示的两种方式编写相同的表达式.例如,您不能使用 &
来引用存储在枚举变体中的值:您需要对其进行匹配.例如,如果你想引用一个Some
中的值,你需要写:
It's not always possible to write the same expression in two ways as shown here, however. For example, you cannot use &
to take a reference to a value stored in an enum variant: you need to match on it. For example, if you want to take a reference to the value in a Some
, you need to write:
match option {
Some(ref value) => { /* stuff */ }
None => { /* stuff */ }
}
由于在 Rust 中无法使用 &
运算符来访问值.
since there's no way in Rust you can use the &
operator to access the value otherwise.
这篇关于`&` 和 `ref` 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!