为什么人们在Go语言中使用内部函数?

huangapple go评论73阅读模式
英文:

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 &lt;-s.stop:
						unsubscribe &lt;- id
						return
					default:
					}

					select {
					case &lt;-s.stop:
						unsubscribe &lt;- id
					case s.events &lt;- e:
					case &lt;-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 &lt;-s.stop:
						unsubscribe &lt;- id
						return
					default:
					}

					select {
					case &lt;-s.stop:
						unsubscribe &lt;- id
					case s.events &lt;- e:
					case &lt;-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.

huangapple
  • 本文由 发表于 2023年1月3日 14:23:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/74989694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定