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

时间:2016-04-07 04:57:27

标签: 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);
}

外壳:

&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

1 个答案:

答案 0 :(得分:7)

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

let tmp = &test;

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