英文:
why do people use inner function in golang?
问题
我正在阅读一些开源的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):
}
}
请注意,我只提供了代码的翻译部分,不包括其他内容。
英文:
I am reading some open source go project and found there are many code implemented as below:
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)
}
in above code, the inner function go func...(id, s)
looks like unnecessary. In other words, what the different if I write code like below:
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):
}
}
答案1
得分: 1
在你的第一个示例中,那是一个使用go
关键字作为goroutine的匿名函数,它是Go语言中的一种并发模式。因此,匿名函数(goroutine)中的代码将同时进行处理。
在你的第二个示例中,不包含goroutine意味着代码将按顺序运行。
匿名函数是一个没有名称的函数。它通常用于创建内联函数。它可以形成闭包。匿名函数也被称为函数字面量。
英文:
In your first example, that is an anonymous function with the go
keyword causing it to function as a goroutine, which is a concurrency pattern in Go. So the code inside the anonymous function (the goroutine) will all process concurrently.
In your second example, excluding the goroutine means the code will run sequentially.
An anonymous function is a function which doesn’t contain any name. It is often used when you want to create an inline function. It can form a closure. An anonymous function is also known as a function literal.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论