2014-02-05 30 views
5

鏽病教程經常主張用鏽:通過參照自動傳遞

fn myFunc(x : &Something) -> .... 

通過引用傳遞的參數。這使得有必要,在呼叫現場,明確地把得到的值參考:

myFunc(&myValue). 

但我檢查,並且可以使用通常的模式匹配用來做「裁判」關鍵字:

fn myFunc(ref x : Something) -> .... 

然後,我可以簡單地通過做叫它

myFunc(myValue) 

內存明智的,做這項工作就像我想到還是它調用myFunc的前棧上覆制myvalue的,然後得到一個參考到副本?

回答

11

該值被複制,然後複製被引用。

fn f(ref mut x: int) { 
    *x = 12; 
} 

fn main() { 
    let mut x = 42; 
    f(x); 
    println!("{:d}", x); 
} 

輸出:42

3

如果調用像f(x)一個函數,那麼x總是按值傳遞。

fn f(ref x: int) { 
    // ... 
} 

相當於

fn f(tmp: int) { 
    let ref x = tmp; 
    // or, 
    let x = &tmp; 

    // ... 
} 

即引用被完全限制在函數調用。

5

這兩個函數聲明x&Something。不同之處在於,前者採用引用或擁有的框作爲參數,而後者則希望它成爲常規堆棧值。爲了說明:

struct Something; 

fn by_reference(x: &Something) { 
    println!("{:?}", x); // prints "&Something"" 
} 

fn on_the_stack(ref x: Something) { 
    println!("{:?}", x); // prints "&Something"" 
} 

fn main() { 
    let value_on_the_stack: Something = Something; 
    let owned: ~Something = ~Something; 
    let borrowed: &Something = &value_on_the_stack; 

    // Compiles: 
    on_the_stack(value_on_the_stack); 

    // Fail to compile: 
    // on_the_stack(owned); 
    // on_the_stack(borrowed); 

    // Dereferencing will do: 
    on_the_stack(*owned); 
    on_the_stack(*borrowed); 

    // Compiles: 
    by_reference(owned); 
    by_reference(borrowed); 

    // Fails to compile: 
    // by_reference(value_on_the_stack); 

    // Taking a reference will do: 
    by_reference(&value_on_the_stack); 
} 

由於on_the_stack取一個值,它被複制,則複製反對在正式參數(在你的榜樣ref x)的模式相匹配。該匹配將x綁定到對複製值的引用。