首页 > 解决方案 > 在单值上下文中执行多值

问题描述

我有一个返回 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并且在 go 例程的情况下,将结构make用于channel

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

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

标签: go

解决方案


通道只能采用一个变量,因此您是正确的,您需要定义一个结构来保存结果,但是,您实际上并没有使用它来传递到您的通道中。您有两个选择,要么修改executeCmd为返回 a 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

推荐阅读