Go 决策(if、if-else、嵌套 if、if-else-if)

go programmingserver side programmingprogramming更新于 2025/5/27 16:22:17

决策是编程的一个重要方面,Go 提供了多种结构来在代码中做出决策。在本文中,我们将探讨 Go 中不同类型的决策结构,包括 if、if-else、嵌套 if 和 if-else-if 结构。

if 语句

Go 中的 if 语句用于仅在某个条件为真时执行代码块。以下是一个例子 -

示例

package main

import "fmt"

func main() {
   x := 10
   
   if x > 5 {
      fmt.Println("x is greater than 5")
   }
}

输出

x is greater than 5

此程序将输出 x is greater than 5,因为条件 x > 5 为真。

if-else 语句

Go 中的 if-else 语句用于在某个条件为真时执行一个代码块,在条件为假时执行另一个代码块。以下是示例 −

示例

package main

import "fmt"

func main() {
   x := 10
   
   if x > 5 {
      fmt.Println("x is greater than 5")
   } else {
      fmt.Println("x is less than or equal to 5")
   }
}

输出

x is greater than 5

此程序将输出 x is greater than 5,因为条件 x > 5 为真。

嵌套 if 语句

Go 中的嵌套 if 语句用于检查多个条件。以下是示例 −

示例

package main

import "fmt"

func main() {
   x := 10
   y := 20

   if x == 10 {
      if y == 20 {
         fmt.Println("x is 10 and y is 20")
      }
   }
}

输出

x is 10 and y is 20

此程序将输出 x is 10 和 y is 20,因为两个条件均为真。

if-else-if 语句

Go 中的 if-else-if 语句用于检查多个条件并根据条件执行不同的代码块。以下是示例 −

示例

package main

import "fmt"

func main() {
   x := 10
   
   if x > 10 {
      fmt.Println("x is greater than 10")
   } else if x < 10 {
      fmt.Println("x is less than 10")
   } else {
      fmt.Println("x is equal to 10")
   }
}

输出

x is equal to 10

此程序将输出 x 等于 10,因为条件 x == 10 为真。

结论

在本文中,我们探讨了 Go 中不同类型的决策构造,包括 if、if-else、嵌套 if 和 if-else-if 构造。这些构造对于编写可以根据用户输入、系统状态和其他因素做出决策的程序至关重要。


相关文章