I have a function returning 2 values: string
and []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
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
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. 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
:
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:
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