当我添加多个'&'时,为什么变量的地址会发生变化?

Ang*_*gel 2 rust

我想了解什么时候使用ref,并&以及时,他们是可以互换的.在另一个代码示例中,我使用了错误的数量&,但是做了一些测试,我发现它有时会起作用.以此代码为例:

fn main() {
    let test        = 5;
    let ref testRef = test;

    println!("&test             as *const _ {:?}", &test     as *const _);
    println!("&testRef          as *const _ {:?}", &testRef  as *const _);
    println!("&*testRef         as *const _ {:?}", &*testRef as *const _);

    println!("&&&&&&&&&&testRef as *const _ {:?}", &&&&&&&&&&testRef as *const _);
    println!("&&&&&testRef      as *const _ {:?}", &&&&&testRef      as *const _);
    println!("&&&&&&*testRef    as *const _ {:?}", &&&&&&*testRef    as *const _);

    println!("&&&&&&&&&&testRef             {:?}", &&&&&&&&&&testRef);
    println!("&&&&&testRef                  {:?}", &&&&&testRef);
    println!("&&&&&&*testRef                {:?}", &&&&&&*testRef);
}
Run Code Online (Sandbox Code Playgroud)

贝壳:

&test             as *const _ 0x7fffac2d5be4   <- this no problem I understand
&testRef          as *const _ 0x7fffac2d5bd8   <- this no problem I understand
&*testRef         as *const _ 0x7fffac2d5be4   <- this no problem I understand

&&&&&&&&&&testRef as *const _ 0x7fffac2d5998   <- why this found and 
&&&&&testRef      as *const _ 0x7fffac2d58f0   <- It changes every 
&&&&&&*testRef    as *const _ 0x7fffac2d5840   <- time you add &

&&&&&&&&&&testRef             5
&&&&&testRef                  5
&&&&&&*testRef                5
Run Code Online (Sandbox Code Playgroud)

oli*_*obk 7

当您&对不仅仅是变量路径的表达式使用运算符时,Rust实际上会创建一个临时的未命名变量,为其指定表达式的结果并为您提供对临时变量的引用.所以,如果你这样做&&test,Rust会创建一个临时的(让我们称之为tmp):

let tmp = &test;
Run Code Online (Sandbox Code Playgroud)

然后Rust给你&tmp,显然有一个新的内存位置.