的生命週期內有效我得到一生錯誤,並且無法理解問題是什麼。這是造成錯誤的代碼是:引用必須在塊的定義爲
fn fetch_git_repo<'a>(repo_info: &RepoInfo) -> &'a TempDir {
let q: TempDir = TempDir::new("temp_git_clone_dir").ok().unwrap();
//let path: &str = dir.path().to_str().unwrap();
let status = Command::new("git").arg("clone").arg(q.path().to_str().unwrap())
.arg(&repo_info.repo_url).status().unwrap_or_else(|e| {
panic!("Failed to run git clone: {}", e)
});
if !status.success() {
panic!("Git clone failed!");
}
&q
}
和錯誤本身是:
test.rs:88:6: 88:7 error: `q` does not live long enough
test.rs:88 &q
^
test.rs:75:60: 89:2 note: reference must be valid for the lifetime 'a as defined on the block at 75:59...
test.rs:75 fn fetch_git_repo<'a>(repo_info: &RepoInfo) -> &'a TempDir {
test.rs:76 let q: TempDir = TempDir::new("temp_git_clone_dir").ok().unwrap();
test.rs:77 //let path: &str = dir.path().to_str().unwrap();
test.rs:78
test.rs:79 let status = Command::new("git").arg("clone").arg("")
test.rs:80 .arg(&repo_info.repo_url).status().unwrap_or_else(|e| {
...
test.rs:76:70: 89:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 76:69
test.rs:76 let q: TempDir = TempDir::new("temp_git_clone_dir").ok().unwrap();
test.rs:77 //let path: &str = dir.path().to_str().unwrap();
test.rs:78
test.rs:79 let status = Command::new("git").arg("clone").arg("")
test.rs:80 .arg(&repo_info.repo_url).status().unwrap_or_else(|e| {
test.rs:81 panic!("Failed to run git clone: {}", e)
什麼是與此功能的問題?
如果我將賦值更改爲「let q:&'TempDir =&Tempdir ....」它仍然給我那個錯誤。我如何解決這個問題? – hunterboerner 2015-04-05 17:11:05
是否確定要返回參考?爲什麼不按值返回'q'? – fjh 2015-04-05 17:13:22
@hunterboerner,你根本不能返回一個對局部變量的引用。如果你這樣做,這個變量就會被銷燬,你將留下一個懸而未決的參考 - 這正是Rust想要阻止的。在C++中,這樣的代碼可能會給你一個段錯誤。 – 2015-04-05 19:13:12