亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在單值上下文中使用多值

在單值上下文中使用多值

Go
躍然一笑 2023-05-04 17:42:19
我有一個返回 2 個值的函數:string和[]stringfunc executeCmd(command, port string, hostname string, config *ssh.ClientConfig) (target string, splitOut []string) {...  return hostname, strings.Split(stdoutBuf.String(), " ")}這個函數被傳遞到一個go routine channelch  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 的初學者,我不明白自己做錯了什么。我見過其他人遇到與我類似的問題,但不幸的是,所提供的答案對我來說沒有意義
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

該通道只能采用一個變量,因此您需要定義一個結構來保存結果是正確的,但是,您實際上并沒有使用它來傳遞到您的通道中。您有兩個選擇,要么修改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


查看完整回答
反對 回復 2023-05-04
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號