「Go/条件分岐と繰り返し」の版間の差分

削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
タグ: 2017年版ソースエディター
Ef3 (トーク | 投稿記録)
→‎selecth文: コード例
タグ: 2017年版ソースエディター
139 行
==== selecth文 ====
selecth文はswitch文と似ていますが、通信チャンネルの並行待ちを行います。
 
;[https://paiza.io/projects/WoJ_v8HVA9Apbht5JtDckQ?language=go Select文を使ったタイムアウト]:<syntaxhighlight lang="go" line>
package main
 
import (
"fmt"
"time"
)
 
func main() {
done := make(chan bool)
go func(s int) {
fmt.Printf("#%d..do\n", s)
time.Sleep(time.Duration(s) * time.Second)
fmt.Printf("#%d..done\n", s)
done <- true
}(2)
select {
case <-done:
fmt.Println("Done!")
case <-time.After(1 * time.Second):
fmt.Println("Timeout!")
}
}
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
#2..do
Timeout!
</syntaxhighlight>
 
=== イテレート - for文 ===