rust - 有条件地将命令的标准输出转换为字符串的寿命不够长
问题描述
我正在编写一个需要使用which
. 我已经知道如何运行命令,但我无法将它存储output.stdout
到我可以使用的变量中。
use std::process::Command;
use std::str;
fn main() {
let interpreter: &str = "php72";
let binary: &str = "composer";
let mut _binary_path: &str = "";
if interpreter != "" {
let output = Command::new("which")
.arg(binary)
.output()
.expect("Execution of 'which' failed.");
_binary_path = str::from_utf8(&output.stdout).unwrap();
}
}
这会导致以下错误:
error[E0597]: `output.stdout` does not live long enough
--> src/main.rs:14:40
|
14 | _binary_path = str::from_utf8(&output.stdout).unwrap();
| ^^^^^^^^^^^^^ borrowed value does not live long enough
15 | }
| - `output.stdout` dropped here while still borrowed
16 | }
| - borrowed value needs to live until here
尽管我已经阅读了文档,但借用和引用仍然让我有些困惑。我知道输出的生命周期是有限的,因为它存在于if
语句中。我不明白为什么它不允许我将值复制到main()
函数的范围内。
这是怎么回事?阅读标准输出的最佳方法是什么?
解决方案
binary_path
是 a&'static str
因为它被初始化为字符串文字。调用的结果str::from_utf8
是 a&str
的生命周期比这短。你不能让价值活得更久。这是 Rust 存在的一个重要原因。
您可以做的最简单的事情是切换到 a String
:
let mut binary_path = String::new();
if interpreter.is_empty() {
// ...
binary_path = String::from_utf8(output.stdout).unwrap();
}
Cow
如果您对总是分配binary_path
性能不佳的基准进行基准测试,您也可以使用。
也可以看看:
推荐阅读
- linux - 如何安装ubuntu统一
- python - 爬取谷歌图片搜索Python(requests、beautifulsoup)
- c# - 什么取代了 asp.net 核心中的 OnAuthorization 方法
- swift - @State 与 @ObservableObject - 哪个以及何时?
- javascript - Javascript Dom按钮onclick函数在页面加载时工作为什么?
- python - np.prod 与 pint.UnitRegistry() 的单位 - python
- python - 从 StratifiedKFold 中的每个折叠中获取多个拆分
- pandas - Streamlit + Panda Dataframe:更改日期的显示方式
- html - 响应式输入组件边距
- python - 循环和列表 - 攻击的基础