2014-09-05 17 views
1

我開始玩弄生鏽,並且在我的測試之一,並做了下面的代碼:以上如何返回可變引用?

fn main() { 
    match std::io::Command::new("ls").arg("/mnt").output() { 
     Ok(o) => println!("ls /mnt:\n{}", String::from_utf8_lossy(o.output.as_slice())), 
     Err(e) => fail!("Ops! {}", e), 
    }; 
    match std::io::Command::new("ls").arg("/media").output() { 
     Ok(o) => println!("ls /media: {}", String::from_utf8_lossy(o.output.as_slice())), 
     Err(e) => fail!("Ops! {}", e), 
    }; 
} 

的代碼工作正常。

然後我決定做一個函數來返回我正在實例化的命令,因爲它們非常相似。例如:

fn main() { 
    match ls("/mnt").output() { 
     Ok(o) => println!("ls /mnt:\n{}", String::from_utf8_lossy(o.output.as_slice())), 
     Err(e) => fail!("Ops! {}", e), 
    }; 
    match ls("/media").output() { 
     Ok(o) => println!("ls /media: {}", String::from_utf8_lossy(o.output.as_slice())), 
     Err(e) => fail!("Ops! {}", e), 
    }; 
} 

fn ls(path: &str) -> &std::io::Command { 
    std::io::Command::new("ls").arg(path) 
} 

這一個不起作用。我得到了reference must be valid for the anonymous lifetime defined on the block at 12:39 ...but borrowed value is only valid for the block at 12:39

好吧,我想我明白了。問題是arg返回的生存期綁定到ls函數作用域,因此在返回時出現編譯錯誤(對嗎?)。

我試過使用沒有成功的方塊。我相信使它工作我應該使用named lifetime,但我說實話,我沒有(但)得到這個概念。

如何將ls中創建的Command超出其範圍?

我正在使用rustc 0.12.0。不要限制自己在你的答案中使用C++ stuff,我有一些經驗。

回答

3

由於您創建的命令位於ls()的範圍內,因此無法返回對其的引用:該命令將超出範圍,並且引用將無效。你必須返回Command對象本身。

由於.arg(path)返回&mut引用您的Command對象,根本不使用它的輸出:

fn ls(path: &str) -> std::io::Command { 
    let mut cmd = std::io::Command::new("ls"); 
    cmd.arg(path); 
    cmd 
} 

arg()返回&mut參考僅僅是一個辦法簡單地IT連鎖,像這樣的事實:

cmd.arg("arg1").arg("arg2").arg("arg3") 
+0

這太簡單了,我覺得有點愚蠢:p ty順便:) – talles 2014-09-05 15:24:30