LoginSignup
1
0

More than 5 years have passed since last update.

closeしたchannelでループを停止する2つの方法

Posted at

channelの戻り値を2つ取って、2つ目で判定してbreakする方法を使っていました。

func(channel chan int) {
    for {
        c, open := <-channel
        if !open {
            break
        }
        // 仕事
        fmt.Println(c)
    }
    // close後の後片付け
}

実行例:https://play.golang.org/p/m3OcAeynaC

channel自体に、for c :=range channelとすることで、この機能が働くことを最近知りました。とってもシンプル。

func(channel chan int) {
    for c := range channel {
        // 仕事
        fmt.Println(c)
    }
    // close後の後片付け
}

実行例:https://play.golang.org/p/p-vEpLFKFH

複数のchannelをリスンする場合は駄目だけど、1つのchannelの場合はこれを使おう。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0