我开始尝试使用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++ 的东西,我有一些相关经验。