GoLang流程控制

条件语句

单分支判断

score := 80
if score >= 60 {
    fmt.Println("及格了")
}

双分支判断

score := 80
if score >= 60 {
    fmt.Println("及格了")
}else {
    fmt.Println("不及格")
}

多分支判断

score := 80
if score >= 80 {
    fmt.Println("优秀")
} else if score >= 60 {
    fmt.Println("及格了")
} else {
    fmt.Println("不及格")
}

选择语句 switch

grade := "B"
switch grade {
case "A":
    fmt.Println("Your score is between 90 and 100.")
case "B":
    fmt.Println("Your score is between 80 and 90.")
case "C":
    fmt.Println("Your score is between 70 and 80.")
case "D":
    fmt.Println("Your score is between 60 and 70.")
default:
    fmt.Println("Your score is below 60.")
}

循环语句 for

// for 接三个表达式
for initialisation; condition; post {
   code
}

// for 接一个条件表达式
for condition {
   code
}

// for 接一个 range 表达式
for range_expression {
   code
}

// for 不接表达式
for {
   code
}
func f1() {
    for i := 1; i <= 10; i++ {
        fmt.Printf("%v\n", i)
    }
}
func f2() {
    i := 1
    for ; i <= 10; i++ {
        fmt.Printf("%v\n", i)
    }
}
func f3() {
    i := 1
    for i <= 10 {
        fmt.Printf("%v\n", i)
        i++
    }
}
func f4() {
    var v = [...]int{1, 2, 4, 5, 7}
    var k = [2]string{"hello", "word"}
    v[1] = 100
    fmt.Println(v[1])
    for _, i := range v {
        fmt.Printf("%v\n", i)
    }
    for _, a := range k {
        fmt.Printf("%v\n", a)
    }
}

break 语句

break 语句用于终止 for 循环,之后程序将执行在 for 循环后的代码。上面的例子已经演示了 break 语句的使用。

continue 语句

continue 语句用来跳出 for 循环中的当前循环。在 continue 语句后的所有的 for 循环语句都不会在本次循环中执行,执行完 continue 语句后将会继续执行一下次循环。 defer 语句 含有 defer 语句的函数,会在该函数将要返回之前,调用另一个函数。简单点说就是 defer 语句后面跟着的函数会延迟到当前函数执行完后再执行 goto 在 Go 语言中保留 goto 。goto 后面接的是标签,表示下一步要执行哪里的代码。


GoLang流程控制
http://www.jcwit.com/article/130/
作者
Carlos
发布于
2022年7月17日
许可协议