go 1.31 流程控制

  1. if语句
  2. switch
  3. for循环
  4. continue跳出本次循环,进入下一次循环
  5. break跳出循环,如果多层嵌套循环,跳出最近的那个内循环

if语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func main() {

/* 定义局部变量 */
var d int = 10

/* 使用 if 语句判断布尔表达式 */
if d == 10 {
/* 如果条件为 true 则执行以下语句 */
fmt.Println("d == 10")
} else {
fmt.Println("d != 10")
}

//if 中的局部变量
// d的作用域只在if的范围内有效
if d:=10 ;d == 10 {
fmt.Println("d == 10")
} else {
fmt.Println("d != 10")
}

}
1
2
3
4
5
6
7
8
9
10
var e int = 9
if e == 10 {
fmt.Println("d == 10")
} else if e > 10 {
fmt.Println("e > 10")
} else if e < 10 {
fmt.Println("e < 10")
} else {
fmt.Println("这是不可能的")
}

switch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main

import (
"fmt"
)

func main() {
var num int
fmt.Printf("please input floor number:")
fmt.Scan(&num)
switch num { //switch 后面是变量本身
// switch num := 5; num { //switch 支持一个初始化语句,用;分隔
case 1, 5:
fmt.Println("case is 1 or 5")
fallthrough // 不跳出switch语句,后面的条件无条件地执行
case 2:
fmt.Println("case is :", 2)
case 3:
fmt.Println("case is :", 3)
case 4:
fmt.Println("case is :", 4)
default:
fmt.Println("this is default case")
}

// case 判断一个表达式
var grade string
fmt.Printf("please input grade:")
fmt.Scan(&grade)
switch {
case grade == "A":
fmt.Printf("优秀!\n")
case grade == "B", grade == "C":
fmt.Printf("良好\n")
fallthrough // 不跳出switch语句,下一句case无条件地执行
case grade == "D":
fmt.Printf("及格\n")
fallthrough // 不跳出switch语句,下一句case无条件地执行
case grade == "F":
break //跳出switch
fmt.Printf("不及格\n")
default:
fmt.Printf("差\n")
}
fmt.Printf("你输入的grade:%s\n", grade)

}

for循环

格式:
for 初始条件;判断条件;条件变化 {

}
或使用range迭代,下标从0开始
for index,data := range iterable_obj {

}

1
2
3
4
5
sum := 0
for i := 1; i < 10; i++ {
sum = sum + i
fmt.Println(sum)
}

1
2
3
4
str := "abc"
for i, data := range str {
fmt.Printf("The No. %d element is: %c\n", i, data)
}

使用_丢弃返回的下标

1
2
3
4
str := "abc"
for _, data := range str {
fmt.Println(data)
}

丢弃返回元素,再通过下标取元素

1
2
3
4
5
6
7
8
str := "abc"
for i, _ := range str {
fmt.Printf("%c\n", str[i])
}
//等价于:
for i := range str {
fmt.Printf("%c\n", str[i])
}

for后面不写任何内容,表示条件永远为值,死循环

1
2
3
4
5
6
7
for {
fmt.Println(i)
if i == 99999 {
break
}
i++
}

continue跳出本次循环,进入下一次循环

break跳出循环,如果多层嵌套循环,跳出最近的那个内循环


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 rootid@126.com

文章标题:go 1.31 流程控制

本文作者:Shawn

发布时间:2019-05-17, 17:48:26

最后更新:2019-05-21, 14:42:41

原始链接:https://gitrootid.github.io/2019/05/17/golang/go-1-31-流程控制_/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏