2016-04-07 23 views
2

ref ve & ne zaman kullanılabileceklerini ve değiştirilebileceğini anlamaya çalışıyorum. Başka bir kod örneğinde yanlış miktarda & kullandım, ancak bazı testler yaparken bunun bazen çalıştığını gördüm. Örnek olarak bu kodu atın:Birden çok '&' eklediğimde neden bir değişkenin adresi değişiyor?

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 

cevap

6

bir değişkene için sadece bir yolu değil bir ifadeye & operatörünü kullandığınızda, Pas aslında geçici bir isimsiz değişken oluşturur, ifadenin sonucunu atar ve size geçici değişkeni referans verir.

let tmp = &test; 

ardından Pas size besbelli yeni bir bellek konuma sahiptir &tmp verir: Eğer &&test yaparsanız, Pas geçici yaratır Yani (haydi tmp diyelim).

İlgili konular