Go 學習筆記02.流程控制 for循環/ if-else判斷/ swith分支

for 循環

for.go

package main

import "fmt"

func main() {

	// 1.常見的for循環
	i := 1
	for i <= 3 {
		fmt.Println(i)
		i = i + 1
	}

	// 2.經典的寫法
	// 初始化條件變量/循環條件/後續執行
	// 經典的初始化/條件/後續形式 `for` 循環。
	for j := 7; j <= 9; j++ {
		fmt.Println(j)
	}

	// 3. 不帶條件的for循環
	// 會在內部無限循環,遇到break/return會跳出
	for {
		fmt.Println("loop")
		break
	}
}

if - else

if-else.go

// `if` 和 `else` 分支結構在 Go 中當然是直接了當的了。

package main

import "fmt"

func main() {

	// 1.---------------------------------------------------
	// 這裏是一個基本的例子。
	// 判斷7是基數odd 還是偶數even
	if 7%2 == 0 {
		// 偶數
		fmt.Println("7 is even")
	} else {
		// 奇數
		fmt.Println("7 is odd")
	}

	// 2.---------------------------------------------------
	// 你可以不要 `else` 只用 `if` 語句。
	if 8%4 == 0 {
		fmt.Println("8 is divisible by 4")
	}

	// 3.---------------------------------------------------
	// 在條件語句之前可以有一個語句;任何在這裏聲明的變量
	// 都可以在所有的條件分支中使用。
	if num := 9; num < 0 {
		fmt.Println(num, "is negative")
	} else if num < 10 {
		fmt.Println(num, "has 1 digit")
	} else {
		fmt.Println(num, "has multiple digits")
	}
}

// 注意,在 Go 中,你可以不使用圓括號,但是花括號是需要的

switch 分支結構

switch.go

package main

import (
	"fmt"
	"time"
)

func main() {

	// 1. ------------------------------------------------
	// 一個基本的 `switch`
    // 輸出 write 2 as two
	i := 2
	fmt.Print("write ", i, " as ")
	switch i {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
	case 3:
		fmt.Println("three")
	}
	

	// 2. ------------------------------------------------
	// 比較的值 必須是同類型的
	// default 不是必須的,上面的都匹配不打牌則執行	;
	fmt.Println(time.Now().Weekday())
	switch time.Now().Weekday() {
	case time.Saturday, time.Sunday:
		fmt.Println("in case")
	default:
		fmt.Println("default")
	}

	// 3. ------------------------------------------------
	// 實現if else效果
	// 不帶表達式的 `switch` 是實現 if/else 邏輯的另一種方式。
	// 這裏展示了 `case` 表達式是如何使用非常量的。
	t := time.Now()
	fmt.Println(t)
	switch {
	case t.Hour() < 12:
		fmt.Println("it's before noon")
	default:
		fmt.Println("it's after noon")
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章