1、if语句

if 条件表达式 {
    执行语句块
} 

注意:条件表达式那里允许声明一个变量,这个变量的作用域只在该条件逻辑块内

func main() {
    if age := 10; age > 9 {
        fmt.Println("Hello, World!")
    } 
}

  

2、if-else语句

if 条件表达式 {
    执行代码块1
} else {
    执行代码块2
}

  

3、if-else if-...=else

if 条件表达式1 {
    执行代码块1
} else if 条件表达式2 {
    执行代码块2
}
...
esle {
    执行代码块n
}

  

4、switch语句

switch 表达式 {
    case 表达式1,表达式2,...:
        代码块1
    case 表达式3,表达式4,...:
        代码块2
	case 表达式4,表达式5,...:
        代码块3
    default:
        代码块n
}

注意:

case后是一个表达式(即:常量值,变量,一个有返回值得函数等都可以)

case后的各个表达式的值得数据类型,必须和switch的表达式的数据类型一致

case后的表达式可以为多个,使用逗号分隔。

case后面的表达式如果是常量值,则要求不能重复

switch默认情况下case最后自带break语句,匹配成功后就不会执行其他case

default语句是不必须的

switch后可以不带表达式,类似if-else分支来使用

func main() {
    var mouth byte = 8	
    switch {
    case 1 <= mouth &&  mouth <4:
        fmt.Println("该月是第一季度")
    case 4 <= mouth &&  mouth < 7 :
	fmt.Println("该月是第二季度")
    case 7 <= mouth &&  mouth < 10 :
	fmt.Println("该月是第三季度")
    case 10 <= mouth &&  mouth <= 12 :
	fmt.Println("该月是第四季度")
    }
}

switch后也可以声明/定义变量,分号结束

func main() {	
    switch mouth := 10; {
    case 1 <= mouth &&  mouth <4:
	fmt.Println("该月是第一季度")
    case 4 <= mouth &&  mouth < 7 :
	fmt.Println("该月是第二季度")
    case 7 <= mouth &&  mouth < 10 :
	fmt.Println("该月是第三季度")
    case 10 <= mouth &&  mouth <= 12 :
	fmt.Println("该月是第四季度")
    }
}

  

posted on 2022-03-02 20:33  smile学子  阅读(101)  评论(0编辑  收藏  举报