doupao1978
2018-11-02 19:00
浏览 33
已采纳

在单值上下文中使用多值

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douchen9569 2018-11-02 21:36
    已采纳

    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
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题