繁体   English   中英

在单值上下文中使用多值

[英]go multiple-value in single-value context

我有一个返回 2 个值的函数: string[]string

func executeCmd(command, port string, hostname string, config *ssh.ClientConfig) (target string, splitOut []string) {

...
  return hostname, strings.Split(stdoutBuf.String(), " ")
}

这个函数被传递到一个 goroutine 通道ch

  ch <- executeCmd(cmd, port, hostname, config)

我知道当你想为单个变量分配 2 个或更多值时,你需要创建一个structure ,在 goroutine 的情况下,使用该结构make一个channel

    type results struct {
        target string
        output []string
    }
  ch := make(chan results, 10)

作为 GO 的初学者,我不明白我做错了什么。 我见过其他人有与我类似的问题,但不幸的是提供的答案对我来说没有意义

通道只能接受一个变量,因此您需要定义一个结构来保存结果是正确的,但是,您实际上并没有使用它来传递到您的通道中。 您有两个选择,要么修改executeCmd以返回results

func executeCmd(command, port string, hostname string, config *ssh.ClientConfig) results {

...
  return results{
    target: hostname, 
    output: strings.Split(stdoutBuf.String(), " "),
  }
}

ch <- executeCmd(cmd, port, hostname, config)

或者保留executeCmd原样并在调用它后将返回的值放入结构中:

func executeCmd(command, port string, hostname string, config *ssh.ClientConfig) (target string, splitOut []string) {

...
  return hostname, strings.Split(stdoutBuf.String(), " ")
}

hostname, output := executeCmd(cmd, port, hostname, config)
result := results{
  target: hostname, 
  output: strings.Split(stdoutBuf.String(), " "),
}
ch <- result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM