`&` 和 `ref` 有什么区别? [英] What's the difference between `&` and `ref`?

查看:54
本文介绍了`&` 和 `ref` 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 & 的工作原理,但它与 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;

这里deref1deref2的类型都是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` 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆