Golang Switch Case 语句:用法示例及详解
Golang 中使用 switch case 语句可以根据不同的条件执行不同的代码块。以下是一个示例:
package main
import "fmt"
func main() {
num := 2
switch num {
case 1:
fmt.Println('num is 1')
case 2:
fmt.Println('num is 2')
case 3:
fmt.Println('num is 3')
default:
fmt.Println('num is not between 1 and 3')
}
}
在上面的示例中,我们定义了一个变量 num,并使用 switch case 语句根据 num 的值执行不同的代码块。如果 num 等于 1,则输出 'num is 1',如果 num 等于 2,则输出 'num is 2',以此类推。如果 num 不在 1 到 3 之间,则输出 'num is not between 1 and 3'。
注意:在 Golang 中,switch case 语句不需要使用 break 语句,因为每个 case 语句块执行完毕后会自动跳出 switch 语句。
原文地址: https://www.cveoy.top/t/topic/naYC 著作权归作者所有。请勿转载和采集!