I'm writing an application that needs to lookup the path of a binary using which
. I already found out how to run a command, but I can't store the output.stdout
to a variable that I can use.
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();
}
}
This results in the following error:
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
Borrowing and referencing is still a bit confusing to me, even though I've read the docs. I understand that the lifetime of output is limited, since it lives in an if
statement. I don't understand why it won't let me copy the value to the scope of the main()
function.
What's going on? What's the best way to read the stdout?