我一直在尝试让一个函数在 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 关注
- 106 浏览
添加回答
举报
0/150
提交
取消