if-else 判断与选择
判断是否为真,为真则执行代码块的输出,为false则不执行。
if true {
fmt.Println("true")
}
选择
func main() {
var str string = "a"
// 要么走第一个代码块,要么走第二个代码块
if str=="a" {
fmt.Println("str = ",str)
}else {
fmt.Println("str != ",str)
}
}
// 多种选择,只会选择一个分支进入并执行对应的代码块,没有找到对应就会进入默认代码块
func main() {
var str int = 0
if str > 0 && str <= 5 {
fmt.Println("str 进入 ~5 范围")
}else if str > 5 && str <=10 {
fmt.Println("str 进入 5 ~10 范围")
}else if str > 10 && str <=100 {
fmt.Println("str 进入 10 ~100 范围")
}else if str > 100 {
fmt.Println("str 进入 100~ 范围")
}else { // 默认代码块
fmt.Println("默认")
}
}
switch 选择
条件语句,将表达式的值与可能匹配的选项列表进行比较,并执行相应的代码块,执行后结束switch。
func main() {
// switch 示例: switch表达式的与case的表达式的值(多个case的值均为唯一的)进行比较,相同则进入对应代码块,没有相匹配的则进入default默认代码块(可省略不写);
i := 3
switch i {
case 1:
fmt.Println(i," -> 1")
case 2:
fmt.Println(i," -> 2")
case 3:
fmt.Println(i," -> 3") //输出: 3 -> 3
case 4:
fmt.Println(i," -> 4")
case 5:
fmt.Println(i," -> 5")
default:
fmt.Println(i," -> default")
}
}
func main() {
// switch 示例
switch i := 3; i { //在switch表达式之前声明初始化i,但i的作用域只限制于switch中
case i: //如果两个的都是i即两个case的值相同i是变量,3是常量,顺序执行第1个。
fmt.Println(i," -> 1")//输出: 3 -> 1
case 2:
fmt.Println(i," -> 2")
case 3:
fmt.Println(i," -> 3")
case 4:
fmt.Println(i," -> 4")
default:
fmt.Println(i," -> default")
}
// fmt.Println(i)
}
func main() {
// switch 示例
i := 3
switch { // switch 表达式可以省略, 默认为true(就可以像if一样判断逻辑,如果都不符合就默认输出)
case i <= 5:
fmt.Println(i," -> 1")//输出: 3 -> 5
case i <= 10:
fmt.Println(i," -> 2")
case i <= 100:
fmt.Println(i," -> 3")
default:
fmt.Println(i," -> default")
}
}
Fallthrough
func main() {
// switch 示例
switch i := getNumber();{// 初始化并赋值i
case i <= 5:
fmt.Println(i," -> 1")
case i <= 10:
fmt.Println(i," -> 2")
fallthrough // fallthrough 接着(case的表达式是多少都会执行)执行后面的代码,只能放置case末尾
case i <= 100: // case false: 也会执行输出:10 -> 3
fmt.Println(i," -> 3")
case i <= 1000:
fmt.Println(i," -> 4")
default:
fmt.Println(i," -> default")
}
}
func getNumber() int {
return 10
}
// 输出:
// 10 -> 2
// 10 -> 3