如何返回可变引用?

时间:2014-09-05 14:39:18

标签: rust

我开始玩锈,并在我的一个测试中做了以下代码:

fn main() {
    match std::io::Command::new("ls").arg("/mnt").output() {
        Ok(o) => println!("ls /mnt:\n{}", String::from_utf8_lossy(o.output.as_slice())),
        Err(e) => fail!("Ops! {}", e),
    };
    match std::io::Command::new("ls").arg("/media").output() {
        Ok(o) => println!("ls /media: {}", String::from_utf8_lossy(o.output.as_slice())),
        Err(e) => fail!("Ops! {}", e),
    };
}

上面的代码工作正常。

然后我决定创建一个函数来返回我实例化的命令,因为它们非常相似。类似的东西:

fn main() {
    match ls("/mnt").output() {
        Ok(o) => println!("ls /mnt:\n{}", String::from_utf8_lossy(o.output.as_slice())),
        Err(e) => fail!("Ops! {}", e),
    };
    match ls("/media").output() {
        Ok(o) => println!("ls /media: {}", String::from_utf8_lossy(o.output.as_slice())),
        Err(e) => fail!("Ops! {}", e),
    };
}

fn ls(path: &str) -> &std::io::Command {
    std::io::Command::new("ls").arg(path)
}

这个不起作用。

我得到reference must be valid for the anonymous lifetime defined on the block at 12:39 ...but borrowed value is only valid for the block at 12:39

好的,我想我明白了。问题是arg返回的生命周期绑定到ls函数范围,因此在返回时会产生编译错误(对吗?)。

我尝试使用盒子但没有成功。我相信要使它工作我应该使用named lifetime但我说实话我没有(还)得到这个概念。

如何将Command中创建的ls返回到其范围之外?

我使用的是rustc 0.12.0。不要限制自己在答案上使用C ++ stuff ,我有一些经验。

1 个答案:

答案 0 :(得分:6)

由于您创建的命令位于ls()的范围内,因此您无法返回对它的引用:该命令将超出范围,并且引用将无效。您必须返回Command对象本身。

.arg(path)返回对&mut对象的Command引用时,只需不要使用其输出:

fn ls(path: &str) -> std::io::Command {
    let mut cmd = std::io::Command::new("ls");
    cmd.arg(path);
    cmd
}

arg()返回&mut引用这一事实只是一种简单链接的方式,如下所示:

cmd.arg("arg1").arg("arg2").arg("arg3")