golang语言switch case

发布于 1 年前 作者 phonegap100 674 次浏览 最后一次编辑是 1 年前 来自 分享

golang语言使用switch语句可方便地对大量的值进行条件判断。 练习:判断文件类型,如果后缀名是.html输入text/html, 如果后缀名.css 输出text/css ,如果后缀名是.js 输出text/javascript Go语言规定每个switch只能有一个default分支。

extname := ".a"

switch extname {

	case ".html":
	
		fmt.Println("text/html")
	
		break
	
	case ".css":
	
		fmt.Println("text/css")
	
		break
	
	case ".js":
	
		fmt.Println("text/javascript")
	
		break
	
	default:
	
		fmt.Println("格式错误")
	
		break

}

Go语言中每个case语句中可以不写break,不加break也不会出现穿透的现象 如下例子:

extname := ".a"
	switch extname {
	case ".html":
		fmt.Println("text/html")
	case ".css":
		fmt.Println("text/css")
	case ".js":
		fmt.Println("text/javascript")
	default:
		fmt.Println("格式错误")
	}

一个分支可以有多个值,多个case值中间使用英文逗号分隔。

n := 2
	switch n {
	case 1, 3, 5, 7, 9:
		fmt.Println("奇数")
	case 2, 4, 6, 8:
		fmt.Println("偶数")
	default:
		fmt.Println(n)
	}

另一种写法:

switch n := 7; n {
	case 1, 3, 5, 7, 9:
		fmt.Println("奇数")
	case 2, 4, 6, 8:
		fmt.Println("偶数")
	default:
		fmt.Println(n)
	}

注意: 上面两种写法的作用域 分支还可以使用表达式,这时候switch语句后面不需要再跟判断变量。例如:

age := 56
	switch {
	case age < 25:
		fmt.Println("好好学习吧!")
	case age > 25 && age <= 60:
		fmt.Println("好好工作吧!")
	case age > 60:
		fmt.Println("好好享受吧!")
	default:
		fmt.Println("活着真好!")
}

switch 的穿透 fallthrought fallthrough`语法可以执行满足条件的case的下一个case,是为了兼容C语言中的case设计的。

func switchDemo5() {
	s := "a"
	switch {
	case s == "a":
		fmt.Println("a")
		fallthrough

	case s == "b":
		fmt.Println("b")
	
	case s == "c":
		fmt.Println("c")
	
	default:
		fmt.Println("...")
	
	}
}
输出:
a
b
var num int = 10
	switch num {
	case 10:
		fmt.Println("ok1")
		fallthrough //默认只能穿透一层
	case 20:
		fmt.Println("ok2")
		fallthrough
	case 30:
		fmt.Println("ok3")
	default:
		fmt.Println("没有匹配到..")
	}
输出:
ok1
ok2
ok3
回到顶部