我正在阅读一些开源go项目,发现有很多代码实现如下:
for id, s := range subscribers {
go func(id string, s *hellosaidsubscriber) {
select {
case <-s.stop:
unsubscribe <- id
return
default:
}
select {
case <-s.stop:
unsubscribe <- id
case s.events <- e:
case <-time.after(time.second):
}
}(id, s)
}
在上面的代码中,内部函数 go func...(id, s)
看起来没有必要。换句话说,如果我编写如下代码会有什么不同:
for id, s := range subscribers {
select {
case <-s.stop:
unsubscribe <- id
return
default:
}
select {
case <-s.stop:
unsubscribe <- id
case s.events <- e:
case <-time.After(time.Second):
}
}
正确答案
在您的第一个示例中,这是一个匿名函数 go
关键字使其充当 goroutine,这是 Go 中的并发模式。因此匿名函数(goroutine)内的代码将同时处理。
在第二个示例中,排除 goroutine 意味着代码将按顺序运行。
匿名函数是不包含任何名称的函数。当您想要创建内联函数时经常使用它。它可以形成闭合。匿名函数也称为函数文字。