0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ゴルーチン⑧DefaultとSelection

Posted at

ゴルーチン⑧DefaultとSelection

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main 
//Default Selection と for break
//for select ループから抜ける

import (
	"fmt"
	"time"
)

func main() {
	//time.Tick,After 時間のchannelを返す
	tick := time.Tick(100 * time.Millisecond)
	boom := time.After(500 * time.Millisecond)


//名前はなんでもいい
OuterLoop:
    for {
		//3-1 あまり良くない例だが
		//isBreak := false
		select {
		//1
		//<- tick  変数がいらない場合はこのように書ける
		case <- tick:
			fmt.Println("1秒")
		case <- boom:
			fmt.Println("5秒")
			//3-1
			//isBreak = True

			//3-2
			//抜ける
			/*
			returnにするとmain()から抜けてしまうため####が表示されない。
			breakだけだと、selectにはbreakがないため、無限ループになる。
			break OuterLoopにすると全ての処理が終わったら抜ける

            同様のことを、ifでやること(3-1)もできるが、望ましくない
			*/
			break OuterLoop
			// return
			
		//2
		//どちらでもない場合
	    default:
			fmt.Println("     .")
			time.Sleep(50 * time.Millisecond)
		}
		//3-0 ここでbreakすると抜けられる。これをやる方法が3-1
		//break

		//3-1 このようにもできるが、3-2へ
		/*if isBreak{
			break
		}*/
	}
	fmt.Println("##############")
}
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?