Skip to content

Instantly share code, notes, and snippets.

@obutora
Created May 21, 2024 12:17
Show Gist options
  • Save obutora/ff8846ad105fd60557f7e98501bb9576 to your computer and use it in GitHub Desktop.
Save obutora/ff8846ad105fd60557f7e98501bb9576 to your computer and use it in GitHub Desktop.
for-selectパターン
package main
import "fmt"
// <- chan int はint型の受信専用チャネル
// この関数は、intを受信する専用のチャネルを返す
func generate(done chan struct{}) <-chan int {
result := make(chan int)
go func() {
defer close(result)
for {
select {
// done channelに値が入ったら終了
// この例では、外部からdoneをcloseすることで終了させる
case <-done:
break
case result <- 1:
}
}
}()
return result
}
func main() {
done := make(chan struct{})
// done channelを渡して、内部で終了させる
result := generate(done)
for i := 0; i < 3; i++ {
fmt.Println(<-result)
}
// done channelをcloseして終了させる
close(done)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment