Home > Mobile >  why do people use inner function in golang?
why do people use inner function in golang?

Time:01-04

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

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related