我被困在看起來像一個簡單問題的東西上。我得到爲什麼我看到錯誤,但似乎無法解決它。顯然我缺少一些基本的東西。在函數中返回由serde_json創建的結構體
fn terraform_deploy_info<'a>(app: &'a MyApp) -> std::result::Result<&MyAppDeployInfo, Error> {
let terraform = process::Command::new("terraform")
// We are querying output values.
.arg("output")
// We want it in json format for easy processing.
.arg("-json")
.output()
.expect("failed to execute terraform");
let output = String::from_utf8_lossy(&terraform.stdout);
let data: TerraformOutputs = serde_json::from_str(&output).unwrap();
let m = data.deploy_info.value.iter().filter(|&x| x.app == "myapp").collect::<Vec<_>>();
if m.len() > 1 {
return Err(Error::MultipleDeployInfo);
}
match m.get(0) {
Some(&x) => Ok(x),
None => Err(Error::NoDeployInfo),
}
}
我得到的錯誤是:
borrowed value must be valid for the lifetime 'a as defined on the body at
這對我來說很有意義,因爲我創造的功能結構和返回借用的引用,這當然會消失,當功能完了。
但,當我改變的返回類型爲std::result::Result<MyAppDeployInfo, Error>
(即,不返回的引用)我似乎無法得到Ok(x)
工作...我得到一個錯誤:
expected struct `MyAppDeployInfo`, found reference
再次,這是有道理的,因爲serde_json
創建一個結構,然後我遍歷引用,所以當我索引到集合中時,我正在查看引用。
所以我嘗試了各種各樣的東西來得到類似於解引用,Box::new
,clone()
,to_owned()
等結構值,仍然無法讓它工作。
我已經在這裏搜索了所有的問題,讀了這本書等,它仍然不清楚我如何解決這個問題......任何指針將不勝感激。
真棒,謝謝! 'into_iter()'並不使用'collect()'是我所缺少的。現在起作用了。 – LegNeato