r/golang•
tommy144p

Can someone explain when the `sndMsg` function is called here?

I was reading a set of slides on Go best practices:

https://talks.golang.org/2013/bestpractices.slide#33

On the linked slide there is the code:

    func broadcastMsg(msg string, addrs []string) error {
        errc := make(chan error)
        quit := make(chan struct{})

        defer close(quit)

        for _, addr := range addrs {
            go func(addr string) {
                select {
                case errc <- **sendMsg**(msg, addr):
                    fmt.Println("done")
                case <-quit:
                    fmt.Println("quit")
                }
            }(addr)
        }

        for _ = range addrs {
            if err := <-errc; err != nil {
                return err
            }
        }
        return nil
    }

I'm still early on in my learning of Go. I can't see when the sndMsg() function, highlighted in bold, is called.

I understand that the for {} loop will iterate indefinitely and in a proper application the quit channel would be used to exit from the for loop.

In the select is sndMsg() called every time case errc <- ... is evaluated?? Furthermore does this call to sndMsg() block the switch statement? Does it block the for loop therefore as well?

Posted Apr 26, 2017, 5:32 PM UTC

112
Loading comments…