Go 語言的循環及條件語句

循環

Go 語言只支持 for 循環。oop

func TestWhileLoop(t *testing.T) {
    n := 0
    for n < 5 {
        n++
        fmt.Println(n)
    }
}

無限循環code

n := 0
for {
    fmt.Println(n)
}

IF條件語句

func TestIf(t *testing.T) {
    if a := 1 == 1; a {
        t.Log("1 == 1")
    }
}

switch 條件語句

Go 語言的 switch 不須要使用 break 來退出一個 caseit

func TestSwitch(t *testing.T) {
    for i := 0; i < 5; i++ {
        switch i {
            case 0, 2:
                t.Log("Even")
            case 1, 3:
                t.Log("Odd")
            default:
                t.Log("not 0-3")
        }
    }
}

case 中使用表達式:io

func TestSwitchCondition(t *testing.T) {
    for i := 0; i < 5; i++ {
        switch {
            case i%2 == 0:
                t.Log("Even")
            case i%2 == 1:
                t.Log("Odd")
            default:
                t.Log("unknow")
        }
    }
}
相關文章
相關標籤/搜索