我有一个返回 2 个值的函数:string
和 []string
func executeCmd(command, port string, hostname string, config *ssh.ClientConfig) (target string, splitOut []string) {
...
return hostname, strings.Split(stdoutBuf.String(), " ")
}
这个函数被传递到一个go例程 channel ch
ch <- executeCmd(cmd, port, hostname, config)
我知道当你想为一个变量分配 2 个或更多值时,你需要创建一个 structure
并且在 go routine 的情况下,使用该结构 make
一个 channel
type results struct {
target string
output []string
}
ch := make(chan results, 10)
作为 GO 的初学者,我不明白自己做错了什么。我见过其他人遇到与我类似的问题,但不幸的是,所提供的答案对我来说没有意义
最佳答案
channel 只能采用一个变量,因此您需要定义一个结构来保存结果是对的,但是,您实际上并没有使用它来传递到您的 channel 中。您有两个选择,要么修改 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
关于在单值上下文中使用多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53124410/