目录
if - else
基本结构:
if 条件式1 {
...
}else if 条件式2{
...
}else if条件式n{
...
}else
...
注:
1.条件式是不需要小括号括起来的
2.条件式中可以添加定义赋值语句
if i := 10;i > 5{
println(i)
}
3.if条件中定义赋值的变量作用域仅在当前if语句中,除了该语句则无法使用
switch
-
case/switch 后是一个表达式(即:常量值、变量、一个有返回值的函数等都可以)
-
case 后的各个表达式的值的数据类型,必须和 switch 的表达式数据类型一致
-
case 后面可以带多个表达式,使用逗号间隔。比如 case 表达式1,表达式2, ...
-
case 后面的表达式如果是常量值(字面量),则要求不能重复
-
case 后面不需要带break,程序匹配到一个 case 后就会执行对应的代码块,然后退出 switch ,如 果一个都匹配不到,则执行 default
-
default 语句不是必须的。
-
switch 后也可以不带表达式,类似 if-else 分支来使用。
-
switch 后也可以直接声明/定义一个变量,分号结束,不推荐。
-
fallthrough,如果在 case 语句块后增加 fallthrough ,则会继续执行下一个 case ,也 叫 switch穿透
-
Type Switch : switch 语句还可以被用于 type switch 来判断某个 interface 变量中实际指向的 变量类型
//7
switch{
case age == 10: ...
case age == 20: ...
}
//8
switch grade := 90;{...}
//9
switch num {
case 10 : ...
fallthrough //只能穿透一层
case 20 : ...
}
//10
var x interface{}
var y = 10.0
x = y
switch i := x.(type) {
case nil:
fmt.Printf("x的类型~:%T",i)
case int:
fmt.Printf("x是int型")
case float64:
fmt.Printf("x是f1oat64型")
case func(int)float64:
fmt.Printf("x是func(int)型")
case bool,string:
fmt.Printf("x是bool或string型")
default:
fmt.Printf("未知型")
}
for
基本结构:
for 初始语句; 条件表达式; 结束语句{
循环体语句
}
注:
1.可以省略初始语句,但必须保留分号
for ;i > 10;i++{
fmt.println(i)
}
2.或者省略初始语句和结束语句和分号
for i > 0{
fmt.println(i)
i--
}
3.无限循环
for {}
4.可以用break跳出for后续循环,用continue跳过本次for循环
5.for-range,多用于遍历字符串和数组
字符串遍历:
传统方式:
var str string = "hello"
for i := 0; i < len(str); i++ {
fmt.Printf("%C \n",str[i])//使用到下标
}
for-range:
var str string = "hello"
for index, val := range str {
fmt.Printf("index=%d,val=%c \n",index,val)
}
注意:
如果我们的字符串含有中文,那么传统的遍历字符串方式,就是错误,会出现乱码。原因是传统的 对字符串的遍历是按照字节来遍历,而一个汉字在 utf8 编码是对应3个字节。
var str string = "hello"
str2 := []rune(str) //即将str转成[]rune
for i := 0; i < len(str2); i++ {
fmt.Printf("%C \n",str2[i]) //使用到下标
}
而for-range则是按照字符方式遍历,因此如果有字符串有中文也是没有问题的