首页 > 解决方案 > 有条件地将命令的标准输出转换为字符串的寿命不够长

问题描述

我正在编写一个需要使用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()函数的范围内。

这是怎么回事?阅读标准输出的最佳方法是什么?

标签: rustcommand

解决方案


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性能不佳的基准进行基准测试,您也可以使用。

也可以看看:


推荐阅读