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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制