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

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

How to assign a the result of `Command::arg()` to a field?

问题

tokio的arg()返回一个对Command的可变引用。如何将其分配给一个字段?

  1. pub struct Manager<'a> {
  2. pub cmd: &'a mut tokio::process::Command,
  3. }
  4. impl<'a> Manager<'a> {
  5. pub fn new() -> Manager<'a> {
  6. Manager {
  7. cmd: &mut tokio::process::Command::new("ls").arg("la"),
  8. }
  9. }
  10. }

错误消息:

返回一个引用当前函数拥有的数据

英文:

tokio's arg() returns a mutable reference to a Command. How can I assign it to a field?

  1. pub struct Manager&lt;&#39;a&gt; {
  2. pub cmd: &amp;&#39;a mut tokio::process::Command
  3. }
  4. impl&lt;&#39;a&gt; Manager&lt;&#39;a&gt; {
  5. pub fn new() -&gt; Manager&lt;&#39;a&gt; {
  6. Manager {
  7. cmd: tokio::process::Command::new(&quot;ls&quot;).arg(&quot;la&quot;)
  8. }
  9. }
  10. }

Error Message:

> returns a value referencing data owned by the current function

答案1

得分: 2

方法返回对同一“Command”的引用,只是为了便于链式方法调用(command.arg("abc").arg("def").spawn())。您也可以忽略其返回值,只需将“Command”分配给字段:

  1. pub struct Manager {
  2. pub cmd: tokio::process::Command,
  3. }
  4. impl Manager {
  5. pub fn new() -> Manager {
  6. let mut cmd = tokio::process::Command::new("ls");
  7. cmd.arg("la");
  8. Manager { cmd }
  9. }
  10. }
英文:

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:

  1. pub struct Manager {
  2. pub cmd: tokio::process::Command,
  3. }
  4. impl Manager {
  5. pub fn new() -&gt; Manager {
  6. let mut cmd = tokio::process::Command::new(&quot;ls&quot;);
  7. cmd.arg(&quot;la&quot;);
  8. Manager { cmd }
  9. }
  10. }

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:

确定