如何返回可变引用?

4

我开始尝试使用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 函数范围内,因此在返回时编译错误(对吧?)。

我尝试使用盒子,但没成功。我相信为了让它工作,我应该使用一个命名生命周期,但是说实话,我还没完全理解这个概念。

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

我正在使用 rustc 0.12.0。在你的回答中,请不要限制自己只使用 C++ 的东西,我有一些相关经验。

1个回答

10

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

由于 .arg(path) 返回对您的 Command 对象的 &mut 引用,因此只需不使用其输出即可:

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")

那太简单了,我感觉有点傻:p 顺便谢谢你:) - talles
这让我花了很长时间才弄明白,非常感谢你! :) - dvdplm
哇,谢谢你——太简单了,我也曾为此苦苦挣扎。感谢你六年后的回复。 - int21h

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接