如何增加绑定的生命周期

时间:2017-03-19 15:31:03

标签: rust lifetime

我有以下代码......

use std::process::Command;

fn main() {
    let cmds = vec![vec!["ls", "-lh"], vec!["grep", "foo"]];
    let mut processes: Vec<&mut Command> = Vec::new();

    let mut i = 0;
    let length = cmds.len();
    while i < length {
        let cmd = cmds[i].clone();
        let mut p = Command::new(&cmd[0]).args(&(cmd[1..]));
        processes.push(p);
        i += 1;
    }
    println!("processes: {:?}", processes);

    // want to manipulate processes elements here again.
    // ...
}

哪个不编译:

error: borrowed value does not live long enough
  --> src/main.rs:11:60
   |
11 |         let mut p = Command::new(&cmd[0]).args(&(cmd[1..]));
   |                     ---------------------                  ^ temporary value dropped here while still borrowed
   |                     |
   |                     temporary value created here
...
19 | }
   | - temporary value needs to live until here
   |
   = note: consider using a `let` binding to increase its lifetime

我明白为什么拒绝编译,我只是不知道在这种情况下如何修复它。

1 个答案:

答案 0 :(得分:1)

您可以存储Command对象本身,而不是存储借用的引用。

let cmds = vec![vec!["ls", "-lh"], vec!["grep", "foo"]];
let mut processes: Vec<Command> = Vec::new();
// ^ you can store concrete objects instead of references.

for cmd in &cmds {
// ^ prefer a `for` loop over a `while` loop. (Also, you don't need to clone the cmds)
    let mut p = Command::new(cmd[0]);
    p.args(&cmd[1..]);
    // ^ you can get a concrete `Command` instead of `&mut Command` reference
    //   if you store the returned object from `new()`.
    processes.push(p);
}

println!("processes: {:?}", processes);
// processes: ["ls" "-lh", "grep" "foo"]