go系列七:条件语句和循环
在Go
中,条件语句和循环语句相对其他语言,那可是太简单了。
判断
if … else
package main
import "fmt"
func main() {
num := 2
if num > 1 {
fmt.Println("num 大于 1")
} else {
fmt.Println("num 不大于 1")
}
}
If … else if … else
package main
import "fmt"
func main() {
num := 2
if num > 2 {
fmt.Println("num 大于 2")
} else if num == 2 {
fmt.Println("num 等于 2")
} else {
fmt.Println("num 小于 2")
}
}
在go中,我们可以将复制判断合并在一起写。
package main
import "fmt"
func main() {
if num := 2; num > 2 {
fmt.Println("num 大于 2")
} else if num == 2 {
fmt.Println("num 等于 2")
} else {
fmt.Println("num 小于 2")
}
}
循环
for
package main
import (
"fmt"
)
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf(" %d", i)
}
}
break 跳转循环
package main
import (
"fmt"
)
func main() {
for i := 1; i <= 10; i++ {
if i == 5 {
break
}
fmt.Printf(" %d", i)
}
}
标签
package main
import (
"fmt"
)
func main() {
outer:
for i := 0; i < 3; i++ {
for j := 1; j < 4; j++ {
fmt.Printf("i = %d , j = %d\n", i, j)
if i == j {
break outer
}
}
}
}
这种方式不建议使用,因为会较少代码的可读性
continue 跳过本次循环
package main
import (
"fmt"
)
func main() {
for i := 1; i <= 10; i++ {
if i == 5 {
continue
}
fmt.Printf(" %d", i)
}
}
在go 中初始化,条件和后置都是可选的
如果我们只保留条件,相当于 其他语言中的while
循环
package main
import (
"fmt"
)
func main() {
i := 0
for i <= 10 {
fmt.Printf(" %d", i)
i += 1
}
}
如果去掉所有可选项,就变成了无限循环。
package main
import "fmt"
func main() {
for {
fmt.Println("Hello World")
}
}
在GO
中还有一个range
这个聊完数组之后再说。
switch
switch经常被用来代替 if … else
package main
import (
"fmt"
)
func main() {
num := 6
switch num {
case 1:
fmt.Println("1")
case 2:
fmt.Println("2")
case 3:
fmt.Println("3")
case 4:
fmt.Println("4")
case 5:
fmt.Println("5")
default: //default case
fmt.Println("没有匹配的")
}
}
default
代表没有匹配时,将执行默认情况, 并且 default
不论放在哪都是最后执行
在Go
中switch
的Case
可以有多个表达式
package main
import (
"fmt"
)
func main() {
num := 9
switch num {
case 1:
fmt.Println("1")
case 2:
fmt.Println("2")
case 3:
fmt.Println("3")
case 4,6,9: //这里有多个表达式
fmt.Println("more number")
case 5:
fmt.Println("5")
default:
fmt.Println("没有匹配的")
}
}
在switch
中可以省略表达式,因此默认为真,所以每个情况都被求值。
func main() {
num := 75
switch {
case num >= 0 && num <= 50:
fmt.Println(num)
case num >= 51 && num <= 100:
fmt.Println( num)
case num >= 101:
fmt.Println( num)
}
}
Fallthrough
fallthrough
会强制执行后面的 case
语句,不会判断下一条 case
的表达式结果是否为 true
。
package main
import (
"fmt"
)
func main() {
switch {
case false:
fmt.Println("1")
fallthrough
case true:
fmt.Println("2")
fallthrough
case false:
fmt.Println("3")
fallthrough
case true:
fmt.Println("4")
case false:
fmt.Println("5")
fallthrough
default:
fmt.Println("6")
}
}
break 跳出switch
package main
import (
"fmt"
)
func main() {
switch num := -5; {
case num < 50:
if num < 0 {
fmt.Printf("break")
break
}
fmt.Println("1")
fallthrough
case num < 100:
fmt.Println("2")
fallthrough
case num < 200:
fmt.Println("3")
}
}
在switch 中也可以像在for 中一样,使用标签,跳出循环,但是不建议使用
本作品采用《CC 协议》,转载必须注明作者和本文链接