deoren / notes

Various notes for topics I'm learning
2 stars 0 forks source link

Golang | range compared to if !ok idiom #59

Open deoren opened 5 years ago

deoren commented 5 years ago

https://play.golang.org/p/ifq754rDA_r

package main

import "fmt"

func main() {
    // empty

}

// section: range
func rangeLoop(m chan string, quit chan struct{}) {
    // loop until the channel is closed
    for m := range messages {
        fmt.Println(m)
    }

    close(quit)
}

// section: range

// section: for
func forLoop(m chan string, quit chan struct{}) {
    // loop until the channel is closed
    for {
        m, ok := <-messages
        if !ok {
            // channel was closed
            break
        }
        fmt.Println(m)
    }
    close(quit)
}