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 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办