英文:
How to assign a the result of `Command::arg()` to a field?
问题
tokio的arg()返回一个对Command的可变引用。如何将其分配给一个字段?
pub struct Manager<'a> {
pub cmd: &'a mut tokio::process::Command,
}
impl<'a> Manager<'a> {
pub fn new() -> Manager<'a> {
Manager {
cmd: &mut tokio::process::Command::new("ls").arg("la"),
}
}
}
错误消息:
返回一个引用当前函数拥有的数据
英文:
tokio's arg() returns a mutable reference to a Command. How can I assign it to a field?
pub struct Manager<'a> {
pub cmd: &'a mut tokio::process::Command
}
impl<'a> Manager<'a> {
pub fn new() -> Manager<'a> {
Manager {
cmd: tokio::process::Command::new("ls").arg("la")
}
}
}
Error Message:
> returns a value referencing data owned by the current function
答案1
得分: 2
方法返回对同一“Command”的引用,只是为了便于链式方法调用(command.arg("abc").arg("def").spawn()
)。您也可以忽略其返回值,只需将“Command”分配给字段:
pub struct Manager {
pub cmd: tokio::process::Command,
}
impl Manager {
pub fn new() -> Manager {
let mut cmd = tokio::process::Command::new("ls");
cmd.arg("la");
Manager { cmd }
}
}
英文:
The method returns a reference to the same Command
it was invoked on, just to make it easy to chain method calls (command.arg("abc").arg("def").spawn()
). You may as well ignore its return value and just assign the Command
to the field:
pub struct Manager {
pub cmd: tokio::process::Command,
}
impl Manager {
pub fn new() -> Manager {
let mut cmd = tokio::process::Command::new("ls");
cmd.arg("la");
Manager { cmd }
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论