[英]go multiple-value in single-value context
I have a function returning 2 values: string
and []string
我有一个返回 2 个值的函数:
string
和[]string
func executeCmd(command, port string, hostname string, config *ssh.ClientConfig) (target string, splitOut []string) {
...
return hostname, strings.Split(stdoutBuf.String(), " ")
}
This function is passed down to a go routine channel ch
这个函数被传递到一个 goroutine 通道
ch
ch <- executeCmd(cmd, port, hostname, config)
I understand that when you want assign 2 or more values to a single variable, you need to create a structure
and in case of go routine, use the structure to make
a channel
我知道当你想为单个变量分配 2 个或更多值时,你需要创建一个
structure
,在 goroutine 的情况下,使用该结构make
一个channel
type results struct {
target string
output []string
}
ch := make(chan results, 10)
Being a beginner in GO, I don't understand what I am doing wrong.作为 GO 的初学者,我不明白我做错了什么。 I have seen other people having similar issue as mine but unfortunately the answers provided did not make sense to me
我见过其他人有与我类似的问题,但不幸的是提供的答案对我来说没有意义
The channel can only take one variable so you are right that you need to define a structure to hold you results, however, you are not actually using this to pass into your channel.通道只能接受一个变量,因此您需要定义一个结构来保存结果是正确的,但是,您实际上并没有使用它来传递到您的通道中。 You have two options, either modify
executeCmd
to return a results
:您有两个选择,要么修改
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)
Or leave executeCmd
as it is and put the values returned into a struct after calling it:或者保留
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.