Home >Backend Development >Golang >Why do people use intrinsic functions in golang?

Why do people use intrinsic functions in golang?

WBOY
WBOYforward
2024-02-06 09:18:09740browse

为什么人们在 golang 中使用内部函数?

Question content

I am reading some open source go projects and found that there are many codes implemented as follows:

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 the above code, the inner function go func...(id, s) seems unnecessary. In other words, what would be the difference if I wrote the following code:

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):
                    }
            }

Correct answer


In your first example, this is an anonymous function go keyword Make it act as a goroutine, which is the concurrency mode in Go. So the code inside the anonymous function (goroutine) will be processed simultaneously.

In the second example, excluding goroutine means that the code will run sequentially.

Anonymous functions are functions that do not contain any name. It is often used when you want to create inline functions. It can form a closure. Anonymous functions are also called function literals.

The above is the detailed content of Why do people use intrinsic functions in golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete