[英]go multiple-value in single-value context
我有一個返回 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
,在 goroutine 的情況下,使用該結構make
一個channel
type results struct {
target string
output []string
}
ch := make(chan results, 10)
作為 GO 的初學者,我不明白我做錯了什么。 我見過其他人有與我類似的問題,但不幸的是提供的答案對我來說沒有意義
通道只能接受一個變量,因此您需要定義一個結構來保存結果是正確的,但是,您實際上並沒有使用它來傳遞到您的通道中。 您有兩個選擇,要么修改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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.