英文:
What is the rationale behind allowing multiple ampersands when referencing a value?
问题
我可以编写这段代码来引用变量 i
的指针:
let i = 10;
let j = &i;
但为什么 Rust 编译器允许在引用变量时使用多个和符号?
示例:
let i = 10;
let j = &&&&&&i; // 这仍然是有效的,指向 i 的引用
英文:
I can write this code to reference the pointer of variable i
:
let i = 10;
let j = &i;
But why does the Rust compiler allow multiple ampersands when referencing a variable?
Example:
let i = 10;
let j = &&&&&&i; // this is still valid and points to reference of i
答案1
得分: 3
在Rust中,引用也是值,因此您可以创建对引用的引用。
let v: i32 = 5;
let r0 = &v; // 指向 `v` 的引用
let r1_1 = &r0; // 指向 r0 的引用。相当于 `&&v`。
let r1_2 = &r0; // 指向 r0 的引用。相当于 `&&v`。
let mut r2 = &r1_1; // 指向 r1_1 的引用。相当于 `&&&v`。
// 因为它是一个值,我们可以改变它!现在它指向 r1_2。相当于 `&&&v`。
r2 = &r1_2;
let another_val = 9;
r2 = &&&another_val;
像 &&&v
这样制作引用是可能的,因为Rust会扩展对临时值的生命周期,如果您对它们进行引用。您可以在规范中了解有关此类信息。
您可以这样思考:
// 原始代码
let v: i32 = 5;
let r = &&&v;
// 编译器生成类似于以下内容:
let v: i32 = 5;
let __r0: &i32 = &v;
let __r1: &&i32 = &__r0;
let r: &&&i32 = &__r1;
英文:
In Rust, references are values too so you can make a reference to a reference.
let v: i32 = 5;
let r0 = &v; // Reference that points to `v`
let r1_1 = &r0; // Reference that points to r0. Equivalent of `&&v`.
let r1_2 = &r0; // Reference that points to r0. Equivalent of `&&v`.
let mut r2 = &r1_1; // Reference that points to r1_1. Equivalent of `&&&v`.
// Because it is a value, we can change it! Now it points to r1_2.
// Equivalent of `&&&v`.
r2 = &r1_2;
let another_val = 9;
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:
// Original code
let v: i32 = 5;
let r = &&&v;
// Compiler generates something like this:
let v: i32 = 5;
let __r0: &i32 = &v;
let __r1: &&i32 = &__r0;
let r: &&&i32 = &__r1;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论