4

Go 语言的循环及条件语句

 3 years ago
source link: https://segmentfault.com/a/1190000040173434
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Go 语言只支持 for 循环。

func TestWhileLoop(t *testing.T) {
    n := 0
    for n < 5 {
        n++
        fmt.Println(n)
    }
}
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 来退出一个 case

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 中使用表达式:

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")
        }
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK