「Go言語」Select文を利用するサンプル
書式
select {
case 条件式1
case 条件式2
}
使用例
package main import ( "fmt" "time" ) func Test(ch chan int, stopCh chan bool) { var m int m = 4 for n := 0; n < 4; n++ { ch <- m time.Sleep(time.Second) } stopCh <- true } func main() { ch := make(chan int) c := 0 stopCh := make(chan bool) go Test(ch, stopCh) for { select { case c = <-ch: fmt.Println("Recvice: ", c) fmt.Println("channel: ") case s := <-ch: fmt.Println("Receive: ", s) case _ = <-stopCh: goto end } } end: }
実行結果
>go run sample.go
Receive: 4
Receive: 4
Receive: 4
Recvice: 4
channel: