packagemainimport("fmt")funcmain(){// 必須先定義起始的變數// The most basic type, with a single condition.// 1, 2, 3i:=1fori<=3{fmt.Println(i)i=i+1}// A classic initial/condition/after `for` loop.// 7, 8, 9forj:=7;j<=9;j++{fmt.Println(j)}// initialisation and post are omittedfori<=10{fmt.Printf("%d ",i)i+=2}//multiple initialisation and incrementforno,i:=10,1;i<=10&&no<=19;i,no=i+1,no+1{fmt.Printf("%d * %d = %d\n",no,i,no*i)}// You can also `continue` to the next iteration of// the loop.forn:=0;n<=5;n++{ifn%2==0{continue}fmt.Println(n)}}
infinite loop (while)
12345678910111213141516
packagemainimport("fmt")funcmain(){// `for` without a condition will loop repeatedly// until you `break` out of the loop or `return` from// the enclosing function.// loopfor{fmt.Println("loop")break}}
// 判斷式前,先宣告變數packagemainimport("fmt""runtime")funcmain(){fmt.Print("Go runs on ")switchos:=runtime.GOOS;os{case"darwin":fmt.Println("OS X.")case"linux":fmt.Println("Linux.")default:// freebsd, openbsd,// plan9, windows...fmt.Printf("%s.",os)}}// Go runs on nacl.
123456789101112131415161718192021222324
packagemainimport("fmt""time")funcmain(){fmt.Println("When's Saturday?")today:=time.Now().Weekday()switchtime.Saturday{casetoday+0:fmt.Println("Today.")casetoday+1:fmt.Println("Tomorrow.")casetoday+2:fmt.Println("In two days.")default:fmt.Println("Too far away.")}}// When's Saturday?// Too far away.
Expressionless switch
123456789101112131415161718
packagemainimport("fmt""time")funcmain(){t:=time.Now()switch{// expression is omittedcaset.Hour()<12:fmt.Println("Good morning!")caset.Hour()<17:fmt.Println("Good afternoon.")default:fmt.Println("Good evening.")}}
Multiple expressions in case
12345678910111213141516
packagemainimport("fmt")funcmain(){letter:="i"switchletter{case"a","e","i","o","u"://multiple expressions in casefmt.Println("vowel")default:fmt.Println("not a vowel")}}// vowel
fallthrough
可以遇到條件符合之後,繼續往下走
12345678910111213141516171819202122232425262728
packagemainimport("fmt")funcnumber()int{num:=15*5returnnum}funcmain(){switchnum:=number();{//num is not a constantcasenum<50:fmt.Printf("%d is lesser than 50\n",num)fallthroughcasenum<100:fmt.Printf("%d is lesser than 100\n",num)fallthroughcasenum<200:fmt.Printf("%d is lesser than 200",num)}}// 75 is lesser than 100// 75 is lesser than 200