我一直在嘗試讓一個函數在 golang 通道“內部”被調用(想想 pythons pool.apply_async,我可以在其中排隊加載函數并稍后同時運行它們)。但無濟于事。我讀過的所有內容都讓我相信這應該是可能的,但現在我認為它不是,因為我看到我嘗試的任何錯誤后都出現編譯錯誤。代碼如下(應該是獨立的和可運行的)package mainimport ( "fmt" "math")type NodeSettings struct { Timeout int PanelInt float64 PanelCCT float64 SpotInt float64 SpotCCT float64 FadeTime int Port int}func main() { fmt.Println("Attempting comms with nodes") futures := make(chan func(ip string, intLevel, cctLevel int, ns *NodeSettings), 100) results := make(chan int, 100) ns := NodeSettings{ Timeout: 5, PanelInt: 58.0, PanelCCT: 6800.0, SpotInt: 60.0, SpotCCT: 2000.0, FadeTime: 0, Port: 40056, } spots := []string{"192.168.52.62", ...snipped} panels := []string{"192.168.52.39", ...snipped} for _, ip := range panels { intLevel := math.Round(254.0 / 100.0 * ns.PanelInt) cctLevel := math.Round((7300.0 - ns.PanelCCT) / (7300.0 - 2800.0) * 254.0) fmt.Printf("IP %s was set to %d (=%d%%) and %d (=%d K)\n", ip, int(intLevel), int(ns.PanelInt), int(cctLevel), int(ns.PanelCCT)) futures <- set6Sim(ip, int(intLevel), int(cctLevel), &ns) }最初,我的陳定義是make(chan func(), 100)導致:.\nodesWriteTest.go:52:11: cannot use set6Sim(ip, int(intLevel), int(cctLevel), &ns) (type int) as type func() in send.\nodesWriteTest.go:60:11: cannot use set8Sim(ip, int(intLevel), int(cctLevel), &ns) (type int) as type func() in send我認為這是由于簽名不匹配,但唉,即使有匹配的簽名,我仍然會遇到類似的錯誤:.\nodesWriteTest.go:51:11: cannot use set6Sim(ip, int(intLevel), int(cctLevel), &ns) (type int) as type func(string, int, int, *NodeSettings) in send.\nodesWriteTest.go:59:11: cannot use set8Sim(ip, int(intLevel), int(cctLevel), &ns) (type int) as type func(string, int, int, *NodeSettings) in send開始認為這是不可能的,那么有沒有其他方法可以實現同樣的目標呢?或者我只是不太正確。謝謝。
1 回答

一只萌萌小番薯
TA貢獻1795條經驗 獲得超7個贊
好吧,您要做的是發送 anint
而不是匿名函數func()
,因為您的set6Sim
andset8Sim
語句都返回int
s。這就是編譯器向您拋出該錯誤的原因。
相反,您需要構造一個匿名函數以發送到通道中,如下所示:
futures <- func(ip string, intLevel, cctLevel int, ns *NodeSettings) { set6Sim(ip, int(intLevel), int(cctLevel), ns) }
您的代碼有點難以理解,因為我們不知道您要做什么。因此,即使沒有最小的示例,這也有望為您指明正確的方向,無論您要解決什么問題。
- 1 回答
- 0 關注
- 142 瀏覽
添加回答
舉報
0/150
提交
取消