go语言if、for、switch语句

发布时间 2023-05-29 14:57:37作者: 自然洒脱

单分支

if condition {
    代码块
}
if 5 > 2 {
    fmt.Println("5 greater than 2")
}

Go语言中,花括号一定要跟着if、for、func等行的最后,否则语法出错。

condition必须是一个bool类型,在Go中,不能使用其他类型等效为布尔值。 if 1 {} 是错误的

语句块中可以写其他代码

如果condition为true,才能执行其后代码块

多分支

if condition1 {
    代码块1
} else if condition2 {
    代码块2
} else if condition3 {
    代码块3
} ... {
    ...
} else if conditionN {
    代码块N
} else {
    代码块
}

多分支结构,从上向下依次判断分支条件,只要一个分支条件成立,其后语句块将被执行,那么其他条件都不会被执行

前一个分支条件被测试过,下一个条件相当于隐含着这个条件 一定要考虑一下else分支是有必要写,以防逻辑漏洞

循环也可以互相嵌套,形成多层循环。循环嵌套不易过深。

if score, line := 99, 90; score > line {
 fmt.Println("perfect")
} else {
 fmt.Println("good")
} // score, line作用域只能是当前if语句

// 这种写法中定义的变量作用域只能是当前if或switch。

switch分支// Go语言的switch有别于C语言的switch,case是独立代码块,不能穿透。

a := 20
switch a { // 待比较的是a
case 10:
 fmt.Println("ten")
case 20:
 fmt.Println("twenty")
case 30, 40, 50: // 或关系
 fmt.Println(">=30 and <=50")
default:
 fmt.Println("other")
}
switch a:=20;a { // 待比较的是a
case 10:
 fmt.Println("ten")
case 20:
 fmt.Println("twenty")
case 30, 40, 50: // 或关系
 fmt.Println(">=30 and <=50")
default:
 fmt.Println("other")
}
a := 20
switch { // 没有待比较变量,意味着表达式是true,是布尔型
case a > 0:
 fmt.Println("positive")
case a < 0:
 fmt.Println("negative")
default:
 fmt.Println("zero")
}
switch a := 20; { // 没有待比较变量,意味着表达式是true,是布尔型
case a > 0: // 如果待比较值是true,a > 0如果返回true,就进入
 fmt.Println("positive")
 // fallthrough // 穿透
case a < 0: // 如果待比较值是true,a < 0如果返回true,就进入
 fmt.Println("negative")
default:
 fmt.Println("zero")
}

for循环