- 不需要手动break
- default是找不到case时执行
- 可以对多个case执行同样的操作
operatingSystem := "windows"
switch operatingSystem {
case "windows", "linux":
// do something if the operating system is windows or linux
case "macos":
// do something if the operating system is macos
default:
// do something if the operating system is none of the above
}
- 空switch根据case的真伪选择是否执行
age := 21
switch {
case age > 20 && age < 30:
// do something if age is between 20 and 30
case age == 10:
// do something if age is equal to 10
default:
// do something else for every other case
}
- fallthrough语句实现case继续向下,就像C的switch不写break
age := 21
switch {
case age > 20:
// do something if age is greater than 20
fallthrough
case age > 30:
// Since the previous case uses 'fallthrough',
// this code will now run if age is also greater than 30
default:
// do something else for every other case
}
标签:case,do,20,age,基础,switch,Golang,Switch,something
From: https://www.cnblogs.com/roadwide/p/17134825.html