- if else
建议条件不用()包裹,if{}不能省略,{}中的{必须紧靠着条件
go语言中没有while循环,可以通过for 代替
age := 30if age > 18 {fmt.Println("我是大人")}//另一种写法if age := 99; age > 18 {fmt.Printf("年龄是%v", age)fmt.Println("我是大人1")}/*上面两种写法的区别第一种写法 age是全局变量 第二种是局部变量 只能在if里面使用*/
- for rang(键值循环)
go 语言中 for rang 可以遍历数组、切片、字符串、map和channel
//遍历字符串str := "你好golang"for i, v := range str {// fmt.Println(i, v)fmt.Printf("i=%v,v=%c\n", i, v)}//遍历切片(先当做js中的数组)var array = []string{"php", "nodejs", "go"}for key, val := range array {fmt.Printf("key=%v,val=%v\n", key, val)}
- switch 循环 fallthrough 可以执行满足条件的下一个case
a := 2switch a {case 2:fmt.Println("我是2")}//另一种写方法,区别就是这里a是局部变量switch a := 3; a {case 3:fmt.Println("我是3")}// 一个分支可以有多个值,多个case值用,分割n := 1switch n {case 1, 2, 3, 4:fmt.Println("我不是10")break //golang中break可以写也可以不写case 10:fmt.Println("我是10")break}
- 在多重循环中,可以用label跳出多重循环。
- continue 语句,结束当前循环,进行下一次循环,只能在for循环中使用。
- goto 语句通过标签进行代码间的无条件跳转。可以快速跳出循环、避免重复退出,下面代码打印 我是大人 333 444
f := 44if f > 20 {fmt.Println("我是大人")goto lable3}fmt.Println("11111")fmt.Println("222") lable3:fmt.Println("333")fmt.Println("444")