判断语句if
package main
import "fmt"
func main() {
if number := 7; number < 1 {
fmt.Println(1)
} else if number >= 1 && number <= 10 {
fmt.Println(2)
} else {
fmt.Println(3)
}
}
2
选择语句switch
package main
import "fmt"
func main() {
switch number1 := 3; number1 {
case 1:
fmt.Println(1)
case 3:
fmt.Println(3)
case 5:
fmt.Println(5)
}
//不需要写break,一旦条件符合自动结束
number2 := 6
switch {
case number2 == 2:
fmt.Println(2)
case number2 == 4:
fmt.Println(4)
case number2 == 6:
fmt.Println(6)
//如希望继续执行下一个case,可以使用fallthrough语句
fallthrough
default:
fmt.Println("default")
}
}
3
6
default
循环语句 for
package main
import "fmt"
func main() {
//形式一:
for number1 := 1; number1 < 3; number1++ {
fmt.Printf("number1:%d\n", number1)
}
//形式二:
number2 := 1
for number2 < 3 {
fmt.Printf("number2:%d\n", number2)
number2++ //不能写成 number2 = number2++(++ 与 -- 是作为语句而不是作为表达式)
}
//形式三: for没有条件将无限循环;用break 退出循环
for {
fmt.Println("loop")
break
}
}
number1:1
number1:2
number2:1
number2:2
loop
遍历 range
package main
import "fmt"
func main() {
// range 关键字用于for循环中迭代数组(array)、切片(slice)、通道(channel)或集合(map)的元素
number := [5]string{"a", "b", "c", "d", "e"}
for k, v := range number {
fmt.Println(k, v)
}
/* 省略key的写法
for _, v := range number {
fmt.Println(v)
}
*/
}
0 a
1 b
2 c
3 d
4 e
跳转语句goto, break, continue
- 支持函数内部 goto 跳转, continue 进入一下次循环,break 终止循环
- break 和 continue 都可以配合标签,在多级嵌套循环间跳出.这和 goto 调整执行位置完全不同
- 通常建议往后 goto,避免死循环
package main
import "fmt"
func main() {
for number := 1; number < 5; number++ {
if number == 3 {
break
}
fmt.Println("break:", number)
}
for number := 1; number < 5; number++ {
if number == 3 {
continue
}
fmt.Println("continue:", number)
}
lable1:
for {
for {
//配合标签跳出最外层循环
//标签名是大小写敏感的
break lable1
}
}
fmt.Println("Hello World1")
goto lable2
fmt.Println("Hello World2")
lable2:
fmt.Println("Hello World3")
}
break: 1
break: 2
continue: 1
continue: 2
continue: 4
Hello World1
Hello World3