Created
May 21, 2024 12:17
-
-
Save obutora/ff8846ad105fd60557f7e98501bb9576 to your computer and use it in GitHub Desktop.
for-selectパターン
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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