if 和 else 分支结构在 Go 中当然是直接了当的了。

package main
import "fmt"
func main() {
这里是一个基本的例子。

    if 7%2 == 0 {
        fmt.Println("7 is even")
    } else {
        fmt.Println("7 is odd")
    }
你可以不要 else 只用 if 语句。

    if 8%4 == 0 {
        fmt.Println("8 is divisible by 4")
    }
在条件语句之前可以有一个语句;任何在这里声明的变量都可以在所有的条件分支中使用。

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

Result:

$ go run if-else.go 
7 is odd
8 is divisible by 4
9 has 1 digit

 

坐标: 上一个例子     下一个例子

 

相关文章:

  • 2021-05-26
  • 2021-08-13
  • 2022-03-04
  • 2021-07-02
  • 2021-12-30
  • 2021-06-21
  • 2021-07-24
  • 2021-12-24
猜你喜欢
  • 2021-08-01
  • 2021-07-06
  • 2021-06-11
  • 2021-09-06
  • 2022-02-02
  • 2021-12-19
  • 2021-07-15
相关资源
相似解决方案