Bu örnek bize bir kanalı nasıl kapatabileceğimizi ve sonsuz bir döngüyü nasıl kırabileceğimizi göstermektedir. Eğer alıcı kanalın durumuyla ilgilenmiyorsa (açık/kapalı) açık olan kanalı kapatmanıza gerek yok. Ben şahsen ne olur ne olmaz kapatma yanlısıyım. Bizim örneğimiz, kanaldan güvenli bir şekilde çıkabilmesi için kanalın kapalı olup olmadığını bilmek istiyor. Önemli bir not, kanalı her zaman gönderici kapatır - alıcı değil.


Örnek


Bu örneklerin her ikisi de aynı şeyi yapıyor ama farklılık olsun diye sadece gösteriyorum.


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