go - 在单值上下文中执行多值
问题描述
我有一个返回 2 个值的函数:string
和[]string
func executeCmd(command, port string, hostname string, config *ssh.ClientConfig) (target string, splitOut []string) {
...
return hostname, strings.Split(stdoutBuf.String(), " ")
}
这个函数被传递到一个 goroutine 通道ch
ch <- executeCmd(cmd, port, hostname, config)
我知道,当您想为单个变量分配 2 个或更多值时,您需要创建一个structure
并且在 go 例程的情况下,将结构make
用于channel
type results struct {
target string
output []string
}
ch := make(chan results, 10)
作为 GO 的初学者,我不明白我做错了什么。我见过其他人有与我类似的问题,但不幸的是,提供的答案对我来说没有意义
解决方案
通道只能采用一个变量,因此您是正确的,您需要定义一个结构来保存结果,但是,您实际上并没有使用它来传递到您的通道中。您有两个选择,要么修改executeCmd
为返回 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)
或者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
推荐阅读
- javascript - Token可以从google开发者工具中查看
- python - pandas:用列表替换列中的非空行
- python-3.x - 如果其中一个被旋转,则查找两个矩形是否重叠
- java - Lombok 可以与 JAXB 和 @XmlType propOrder 一起使用吗?
- html - Django轮播一次显示3张图片
- c# - 如何在 C# 的 NumericUpDown 中显示“0000”而不是“0”
- php - 将 preg_replace() 与可能包含特殊字符的搜索词一起使用
- php - 将 WooCommerce 自定义会话变量保存为订单元数据
- iis - IIS 共享配置 > HTTP 错误 500.21
- cassandra - 如何计算 cassandra DB 中的“Concurrent_reads”参数