go基础——for语法
package main
import "fmt"
/*
for循环:某些代码会多次的执行
*/
func main() {
for i := 1; i <= 3; i++ {
fmt.Println(i, "hello world")
}
//省略1,3表达式,只保留2表达式。相当于while条件
j := 1
for j <= 5 {
fmt.Println(j)
j++
}
//同时省略三个表达式,相当于while true,死循环
// for {
// fmt.Println(j)
// j++
// }
//嵌套循环
for m := 0; m < 5; m++ {
for n := 0; n < 5; n++ {
fmt.Print("*")
}
fmt.Println()
}
//break和continue
for x := 1; x < 8; x++ {
if x == 5 {
break
}
fmt.Println(x)
}
fmt.Println("==================")
for x := 1; x < 8; x++ {
if x == 3 || x == 5 {
continue
}
fmt.Println(x)
}
fmt.Println("==================")
//嵌套循环,在内层break/continue外层循环
out: //外层循环命名
for m := 0; m < 5; m++ {
for n := 0; n < 5; n++ {
fmt.Print("*")
if n == 1 {
break out
}
}
fmt.Println()
}
}
执行结果
1 hello world
2 hello world
3 hello world
1
2
3
4
5
*****
*****
*****
*****
*****
1
2
3
4
==================
1
2
4
6
7
==================
**