我一直在尝试在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
}
最初,我的chan定义为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
开始认为这是不可能的,那么还有其他方法可以实现同一目标吗?还是我只是不太正确。谢谢。
答案 0 :(得分:5)
好吧,您要执行的操作是发送int
而不是匿名函数func()
,因为您的set6Sim
和set8Sim
语句都返回{{1} } s。这就是编译器向您抛出该错误的原因。
相反,您需要构造一个匿名函数以发送到通道中,如下所示:
int
您的代码有点难以理解,因为我们不知道您要做什么。因此,如果没有一个简单的例子,希望可以为您提供正确的方向,以解决您要解决的所有问题。