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

Why do people use intrinsic functions in golang?

WBOY
Release: 2024-02-06 09:18:09
forward
738 people have browsed it

为什么人们在 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)
            }
Copy after login

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):
                    }
            }
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template