允许多个”ampersands”引用值时的理由是什么?

huangapple go评论88阅读模式
英文:

What is the rationale behind allowing multiple ampersands when referencing a value?

问题

我可以编写这段代码来引用变量 i 的指针:

  1. let i = 10;
  2. let j = &i;

但为什么 Rust 编译器允许在引用变量时使用多个和符号?

示例:

  1. let i = 10;
  2. let j = &&&&&&i; // 这仍然是有效的,指向 i 的引用
英文:

I can write this code to reference the pointer of variable i:

  1. let i = 10;
  2. let j = &i;

But why does the Rust compiler allow multiple ampersands when referencing a variable?

Example:

  1. let i = 10;
  2. let j = &&&&&&i; // this is still valid and points to reference of i

答案1

得分: 3

在Rust中,引用也是值,因此您可以创建对引用的引用。

  1. let v: i32 = 5;
  2. let r0 = &v; // 指向 `v` 的引用
  3. let r1_1 = &r0; // 指向 r0 的引用。相当于 `&&v`。
  4. let r1_2 = &r0; // 指向 r0 的引用。相当于 `&&v`。
  5. let mut r2 = &r1_1; // 指向 r1_1 的引用。相当于 `&&&v`。
  6. // 因为它是一个值,我们可以改变它!现在它指向 r1_2。相当于 `&&&v`。
  7. r2 = &r1_2;
  8. let another_val = 9;
  9. r2 = &&&another_val;

&&&v 这样制作引用是可能的,因为Rust会扩展对临时值的生命周期,如果您对它们进行引用。您可以在规范中了解有关此类信息。

您可以这样思考:

  1. // 原始代码
  2. let v: i32 = 5;
  3. let r = &&&v;
  4. // 编译器生成类似于以下内容:
  5. let v: i32 = 5;
  6. let __r0: &i32 = &v;
  7. let __r1: &&i32 = &__r0;
  8. let r: &&&i32 = &__r1;
英文:

In Rust, references are values too so you can make a reference to a reference.

  1. let v: i32 = 5;
  2. let r0 = &v; // Reference that points to `v`
  3. let r1_1 = &r0; // Reference that points to r0. Equivalent of `&&v`.
  4. let r1_2 = &r0; // Reference that points to r0. Equivalent of `&&v`.
  5. let mut r2 = &r1_1; // Reference that points to r1_1. Equivalent of `&&&v`.
  6. // Because it is a value, we can change it! Now it points to r1_2.
  7. // Equivalent of `&&&v`.
  8. r2 = &r1_2;
  9. let another_val = 9;
  10. r2 = &&&another_val;

Making reference like &&&v is possible because Rust extends lifetime of temporaries if you take reference to them. You can read about them in specification.

You can think about it like this:

  1. // Original code
  2. let v: i32 = 5;
  3. let r = &&&v;
  4. // Compiler generates something like this:
  5. let v: i32 = 5;
  6. let __r0: &i32 = &v;
  7. let __r1: &&i32 = &__r0;
  8. let r: &&&i32 = &__r1;

huangapple
  • 本文由 发表于 2023年5月6日 23:04:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定