在单值上下文中使用多值

标签 go

我有一个返回 2 个值的函数:string[]string

func executeCmd(command, port string, hostname string, config *ssh.ClientConfig) (target string, splitOut []string) {

...
  return hostname, strings.Split(stdoutBuf.String(), " ")
}

这个函数被传递到一个go例程 channel ch

  ch <- executeCmd(cmd, port, hostname, config)

我知道当你想为一个变量分配 2 个或更多值时,你需要创建一个 structure 并且在 go routine 的情况下,使用该结构 make 一个 channel

    type results struct {
        target string
        output []string
    }
  ch := make(chan results, 10)

作为 GO 的初学者,我不明白自己做错了什么。我见过其他人遇到与我类似的问题,但不幸的是,所提供的答案对我来说没有意义

最佳答案

channel 只能采用一个变量,因此您需要定义一个结构来保存结果是对的,但是,您实际上并没有使用它来传递到您的 channel 中。您有两个选择,要么修改 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)

或者保持 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

关于在单值上下文中使用多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53124410/

相关文章:

go - 检查 nil 后从结构体中赋值

memory-leaks - 这会导致 Go 中的内存泄漏吗?

go - 在双核 cpu 上运行 GO runtime.GOMAXPROCS(4)

pointers - Cgo指针字符串 slice (*[]string)的指针传递规则?

git - 是否可以使用 "go get"获取 git 标签?

xml - 使用属性解码 xml 标签

go - 将一个 slice 分成N个 slice

go - 我们可以在goroutine中实现goroutine吗?

unit-testing - 接收方方法相互调用时的单元测试

amazon-web-services - DynamoDB创建Session的常用函数