您当前的位置:首页 > 计算机 > 编程开发 > Go语言

Go语言的switch case语法详解(附上与PHP的区别)

时间:02-25来源:作者:点击数:
CDSY,CDSY.XYZ

Go和其他语言switch case语法区别

Go的switch case

case匹配执行后,默认跳出判断,不需要 break 关键字。

Go正确写法:

switch e.Name {
        case "a", "b", "c":
            ...
        }

Go错误写法:

switch e.Name {
        case "a":
        case "b":
        case "c":
            ...
        }
PHP的switch case

case匹配执行后,继续执行下个case,跳出不再匹配下一个,要使用 break 关键字

switch (e.Name) {
        case "a":
        case "b":
        case "c":
            ...
        break;
}

golang 的 switch 遇到匹配的 case 后,执行完 case 内的代码会直接 break 出来,而 php 中需要手动 break,否则会一直往下匹配,直到找到中断位置结束。

Go语言常见switch case用法

1. 基本用法
func main() {
	var a = "hello"
	switch a {
	case "aaa":
		fmt.Println(11)
	case "hello":
		fmt.Println(1)
	case "world":
		fmt.Println(2)
	default:
		fmt.Println(0)
	}
}
2. 一分支case多个并列值
package main
 
import (
	"fmt"
)
 
func main() {
	//根据用户输入的月份,打印该月份所属的季节
	var month byte
	fmt.Print("请输入月份:")
	fmt.Scanln(&month)
	switch month {
		case 3, 4, 5:
			fmt.Println("春天")
		case 6, 7, 8:
			fmt.Println("夏天")
		case 9, 10, 11:
			fmt.Println("秋天")
		case 12, 1, 2:
			fmt.Println("冬天")
		default:
			fmt.Println("输入有误...")
	}
}
3. interface{}接口的类型判断

switch a := x.(type): 对于 interface{}接口变量,先赋值保存 变量值 备用,再 case 变量类型

package main
 
import (
	"fmt"
)
 
func main() {
	var x interface{}
	var y = 10
	x=y
	switch i := x.(type) {
	case nil:
		fmt.Printf("x的类型是:%T",i)
	case int:
		fmt.Printf("x是 int 类型")
	case float64:
		fmt.Printf("x是 float64 类型")
	case func(int) float64:
		fmt.Printf("x是func(int)类型")
	case bool,string:
		fmt.Printf("x是bool或者string类型")
	default:
		fmt.Printf("未知型")
	}
}
4. 跨越 case 的 fallthrough

Go语言中 case 执行后,不会接着执行下一个 case,但为了兼容一些移植代码,加入了 fallthrough 关键字。

加了fallthrough 后,会直接运行紧跟的后一个 case 或 default 语句,

package main
import "fmt"
func main() {
	var s = "hello"
	switch {
	case s == "world":
		fmt.Println("world")
	case s == "hello":
		fmt.Println("hello")
		fallthrough
	case s != "world":
		fmt.Println("world")
		fallthrough
	case s == "world":
		fmt.Println("world")
	}

}

5. 分支表达式
age := 19
switch {
case age < 18:
	fmt.Println("未成年")
case age >= 18:
	fmt.Println("已成年")
}

CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门