This example shows us how you can close a channel and break a forever loop. Normally you are not required to close a channel as long as the receiver doesn't depend on the channel state (open/closed). However, I personally would close just in case. Our example needs to know if the channel is closed so that it can safely exit the loop. An important note, always the sender closes the channel - not the receiver.


Example


Both of these examples do the same thing so just showing.


package main

import (
"fmt"
)

func main() {
fmt.Println("begin")

teams := []string{"Fenerbahce", "Arsenal", "Monaco", "Juventus"}

msg := make(chan string)

go list(msg, teams)

// Until the channel is closed, print the received message.
for m := range msg {
fmt.Println(m)
}

fmt.Println("done")
fmt.Println("end")
}

func list(msg chan<- string, teams []string) {
for _, team := range teams {
msg <- fmt.Sprintf("Forza %s!", team)
}

// Close channel to instruct the main goroutine to stop waiting for new messages.
close(msg)
}

package main

import (
"fmt"
)

func main() {
fmt.Println("begin")

teams := []string{"Fenerbahce", "Arsenal", "Monaco", "Juventus"}

msg := make(chan string)

go list(msg, teams)

// Indefinitely wait for the channel to return something.
for {
// Until the channel is closed, print the received message otherwise break the loop.
m, open := <-msg
if !open {
fmt.Println("done")
break
}

fmt.Println(m)
}

fmt.Println("end")
}

func list(msg chan<- string, teams []string) {
for _, team := range teams {
msg <- fmt.Sprintf("Forza %s!", team)
}

// Close channel to instruct the main goroutine to stop waiting for new messages.
close(msg)
}

begin
Forza Fenerbahce!
Forza Arsenal!
Forza Monaco!
Forza Juventus!
done
end