我一直在尝试将一个函数称为"内部"一个golang通道(想想pythons pool.apply_async,我可以将一大堆函数排队并在以后同时运行它们).但无济于事.我读过的所有内容都让我相信这应该是可能的,但现在我认为它不是,因为我看到编译错误后我尝试的任何错误.代码如下(应该是自包含且可运行的)
package main
import (
"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)
}
for _, ip := range spots {
intLevel := math.Round(254.0 / 100.0 * ns.SpotInt)
cctLevel := math.Round((6500.0 - ns.SpotCCT) / (6500.0 - 1800.0) * 254.0)
fmt.Printf("IP %s was set to %d (=%d%%) and %d (=%d K)\n",
ip, int(intLevel), int(ns.SpotInt), int(cctLevel), int(ns.SpotCCT))
futures <- set8Sim(ip, int(intLevel), int(cctLevel), &ns)
}
close(futures)
fmt.Println("Complete")
}
func set6Sim(ip string, intLevel, cctLevel int, ns *NodeSettings) int {
fmt.Println(fmt.Sprintf("Simulated (6) run for IP %s", ip))
return 1
}
func set8Sim(ip string, intLevel, cctLevel int, ns *NodeSettings) int {
fmt.Println(fmt.Sprintf("Simulated (8) run for IP %s", ip))
return 1
}
Run Code Online (Sandbox Code Playgroud)
最初,我的陈定义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
Run Code Online (Sandbox Code Playgroud)
我假设是由于签名不匹配,但唉,即使有匹配的签名我仍然会得到类似的错误:
.\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
Run Code Online (Sandbox Code Playgroud)
开始认为这是不可能的,那么有没有其他方法来实现同样的事情?或者我还没有完全正确.谢谢.
好吧,你要做的是发送一个int而不是一个匿名函数,func()因为你set6Sim和set8Sim语句都返回ints.这就是编译器抛出该错误的原因.
相反,您需要构建一个匿名函数以发送到通道,如下所示:
futures <- func(ip string, intLevel, cctLevel int, ns *NodeSettings) {
set6Sim(ip, int(intLevel), int(cctLevel), ns)
}
Run Code Online (Sandbox Code Playgroud)
您的代码有点难以理解,因为我们不知道您要做什么.因此,如果没有一个最小的例子,这将有希望指出你正确的方向,无论你想要解决什么.