if语法
if statement; condition {
}
func main() {
num := 10
if num%2 == 0 {
fmt.Println("even")
} else {
fmt.Println("odd")
}
}
//even
func main() {
if num := 10; num%2 == 0 {
fmt.Println("even")
} else {
fmt.Println("odd")
}
}
//even
func main() {
num := 99
if num < 50 {
fmt.Println("<50")
} else if num >= 51 && num <= 100 {
fmt.Println("51<=num<=100")
} else {
fmt.Println(">100")
}
}
//51<=num<=100
for initialisation; condition; post {
}
// break: 终止for
func main() {
for i := 0; i < 10; i++ {
if i > 5 {
break
}
fmt.Println(i)
}
}
//1
//2
//3
//4
//5
// continue: 跳过本次循环
func main() {
for i := 0; i < 10; i++ {
if i %2==0 {
continue
}
fmt.Println(i)
}
}
//1
//3
//5
//7
//9
if与switch
func main() {
for i := 0; i < 3; i++ {
if i == 0 {
fmt.Println("0")
}else if i == 1 || i == 2 {
fmt.Println("1 or 2")
} else {
fmt.Println("not 0-2")
}
}
}
//可以改写为:
func main() {
for i := 0; i < 3; i++ {
switch {
case i == 0:
fmt.Println("0")
case i == 1 || i == 2:
fmt.Println("1 or 2")
default:
fmt.Println("not 0-2")
}
}
}
//也可以改写为这样
func main() {
for i := 0; i < 3; i++ {
switch i {
case 0:
fmt.Println("0")
case 1, 2: //任意一个匹配即可
fmt.Println("1 or 2")
default:
fmt.Println("not 0-2")
}
}
}
//对于条件较为复杂 使用
switch{
case i>10 && i<20
}
//default分支不是必须
func main() {
for i := 0; i < 3; i++ {
switch i {
case 0:
fmt.Println("0")
case 1, 2:
fmt.Println("1 or 2")
}
}
}
//default位置可选
func main() {
for i := 0; i < 3; i++ {
switch i {
default:
fmt.Println("not 0-2")
case 0:
fmt.Println("0")
case 1, 2:
fmt.Println("1 or 2")
}
}
}
//case条件不能重复
func main() {
i:=0
switch i {
case 0:
fmt.Println("0")
case 0:
fmt.Println("0")
}
}
//.main.go:10:2: duplicate case 0 in switch
//case后隐含break, 无需手动去break, 一旦匹配一个分支, 即跳出整个switch
func main() {
i := 3
switch {
case i > 0:
fmt.Println("i>0")
case i > 2:
fmt.Println("i>2")
}
}
//i>0
- fallthrough穿透(失效)下一层的条件, 执行下一层语句.
func main() {
i := 1
switch {
case i > 0:
fmt.Println("i>0")
fallthrough
case i > 2:
fmt.Println("i>2")
}
}
//i>0
//i>2
//fallthrough决定该层要不要穿透,如果该层无,则直接break,终结整个switch
func main() {
i := 3
switch {
case i > 0:
fmt.Println("i>0")
case i > 2:
fmt.Println("i>2")
fallthrough
default:
fmt.Println("not 0 1 2 3")
}
}
//i>0
//一旦一层被fallthrough, 其他的条件即使不成立, 也会被执行(无视条件了)
func main() {
i := 1
switch {
case i > 0:
fmt.Println("i>0")
fallthrough
case i > 2:
fmt.Println("i>2")
default:
fmt.Println("not 0 1 2 3")
}
}
//i>0
//i>2
func main() {
i := 0
switch {
case i > 0:
fmt.Println("i>0")
fallthrough
case i > 2:
fmt.Println("i>2")
fallthrough
default:
fmt.Println("not 0 1 2 3")
}
}
//not 0 1 2 3
//fallthrough不允许放最后一个分支
func main() {
i := 1
switch {
case i > 0:
fmt.Println("i>0")
fallthrough
case i > 2:
fmt.Println("i>2")
fallthrough
}
}
//.main.go:13:3: cannot fallthrough final case in switch
//switch满足条件处开始执行
func main() {
s := "abcd"
switch s[2] {
case 'a':
fmt.Println("a")
fallthrough
case 'b':
fmt.Println("b")
fallthrough
case 'c':
fmt.Println("c")
fallthrough
default:
fmt.Println("default case")
}
}
//c
//default case