如何将 `Command::arg()` 的结果分配给一个字段?

huangapple go评论56阅读模式
英文:

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&lt;&#39;a&gt; {
    pub cmd: &amp;&#39;a mut tokio::process::Command
}

impl&lt;&#39;a&gt; Manager&lt;&#39;a&gt; {
    pub fn new() -&gt; Manager&lt;&#39;a&gt; {
        Manager {
            cmd: tokio::process::Command::new(&quot;ls&quot;).arg(&quot;la&quot;)
        }
    }
}

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(&quot;abc&quot;).arg(&quot;def&quot;).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() -&gt; Manager {
        let mut cmd = tokio::process::Command::new(&quot;ls&quot;);
        cmd.arg(&quot;la&quot;);
        Manager { cmd }
    }
}

huangapple
  • 本文由 发表于 2023年7月6日 22:35:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定