循环
for
for 初始语句;条件表达式;结束语句{
循环体语句
}
for 条件 {
循环体
}
死循环
for {
循环体语句
}
for range
Go语言中可以使用for range
遍历数组、切片、字符串、map 及通道(channel)。 通过for range
遍历的返回值有以下规律:
- 数组、切片、字符串返回索引和值。
- map返回键和值。
- 通道(channel)只返回通道内的值。
range关键字输出需要两个变量来接受,相当于Python中enumerate,如果不想要索引可以使用丢弃变量_
来接收.
如果只使用一个变量接收range的返回值,只会返回索引.
break
break
语句可以结束for
、switch
和select
的代码块。
continue
continue
语句可以结束当前循环,开始下一次的循环迭代过程,仅限在for
循环内使用。
判断
if else
if 表达式1 {
分支1
} else if 表达式2 {
分支2
} else{
分支3
}
switch case
switch expr {
case 1:
分支1
case 2:
分支2
fallthrough
default:
分支3
}
func switchdemo1() {
a := 3
switch a {
case 1:
fmt.Println("1")
case 2:
fmt.Println("2")
case 3:
fmt.Println("3")
fallthrough
default:
fmt.Println("x")
}
}
func switchdemo2() {
switch a:=2;a {
case 1:
fmt.Println("1")
case 2:
fmt.Println("2")
fallthrough
case 3,4://3或4都满足田间
fmt.Println("3")
default:
fmt.Println("x")
}
}
func switchdemo3() {
var a = 85
switch {
case a<60 && a>0:
fmt.Println("不及格")
case a<90 && a>=60:
fmt.Println("良好")
case a<=100 && a>=90:
fmt.Println("优秀")
}
}
func main(){
switchdemo1()
switchdemo2()
switchdemo3()
}
------------------------------------------
3
x
2
3
良好
执行到fallthrough
的时候会继续执行其下面的一个分支,无论下面的是case
还是default
当default
前面的分支都没有执行的时候,执行default
中的语句