Angel Angel
Angel Angel

Reputation: 21658

Why does the address of a variable change when I add multiple '&'?

I'm trying to understand when to use ref and & as well as when they are interchangeable. In another code example I used the wrong amount of &, but doing some tests I saw that this works sometimes. Take this code as an example:

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);
}

Shell:

&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

Upvotes: 2

Views: 114

Answers (1)

oli_obk
oli_obk

Reputation: 31163

When you use the & operator on an expression that is not just a path to a variable, Rust actually creates a temporary unnamed variable, assigns it the result of the expression and gives you a reference to the temporary variable. So if you do &&test, Rust creates a temporary (let's call it tmp):

let tmp = &test;

and then Rust gives you &tmp, which obviously has a new memory location.

Upvotes: 7

Related Questions