Skip to content

https://www.cainiaoplus.com/golang/go-if-if-else-nested-if-if-else-if.html

❤️ if

  • if
go
if v < 1000 {
	fmt.Printf("v小于1000\n")
}
  • if … else …
go
if v < 1000 {
	fmt.Printf("v < 1000\n")
} else {
	fmt.Printf("v > 1000\n")
}
  • if … else if … else …
go
if(condition_1) {

} else if(condition_2) {

} else {

}

❤️ for

  • 死循环
go
for {
    fmt.Printf("nhooo\n")
}
  • 基础循环
go
for i := 0; i < 4; i++ {
    fmt.Printf("nhooo\n")
}
  • while 循环
go
// 直到 m 不小于 3,才会停止
m := 0
for m < 3 {
    m += 2
}
  • 增强 for(索引,值)
go
variable := []string{"GFG", "Geeks", "nhooo"}
for i, j := range variable { // i 为索引,j 为值
    fmt.Println(i, j)
}
for i := range variable { // i 为索引
    fmt.Println(i)
}

---

for i, j := range "XabCd" {
    fmt.Printf("%U 的索引值为 %d\n", j, i)
}

U+0058 的索引值为 0
U+0061 的索引值为 1
U+0062 的索引值为 2
U+0043 的索引值为 3
U+0064 的索引值为 4
  • map 循环(key,value)
go
mmap := map[int]string{
    22: "Geeks",
    33: "GFG",
    44: "nhooo",
}
for key, value := range mmap {
    fmt.Println(key, value)
}

22 Geeks
33 GFG
44 nhooo
  • channel 循环 :遍历通道上发送的顺序值,直到关闭为止
go
chnl := make(chan int)
go func() {
    chnl <- 100
    chnl <- 1000
    chnl <- 10000
    chnl <- 100000
    close(chnl)
}()
for i := range chnl {
    fmt.Println(i)
}

100
1000
10000
100000

break,continue,goto

  • goto :一般不使用 goto,难以理解
go
	x := 0

Lable1:
	for x < 4 {
		if x == 2 {
			x++
			goto Lable1
		}
		fmt.Printf("值为: %d\n", x)
		x++
	}

值为: 0
值为: 1
值为: 3
值为: 4

❤️ switch

表达式 switch

  • 无初始化表达式,无判断变量
go
x := 10
switch {
    case x < 5:
        fmt.Println("Less than 5")
    case x == 10:
        fmt.Println("Equal to 10")
}
  • 无初始化表达式,有判断变量
go
x := 10
switch x {
case 1, 2, 3:
	fmt.Println("1")
case 10:
	fmt.Println("10")
default:
	fmt.Println("Default")
}

switch x := 10; {
case x > 5:
  fmt.Println("x 大于 5")
default:
  fmt.Println("x 小于或等于 5")
}
  • 有初始化表达式,有判断变量
go
x := 5
y := 8

switch result := x * y; result {
case 30:
    fmt.Println("Result is 30")
case 40:
    fmt.Println("Result is 40")
}

fallthrough

go
// fallthrough 会强制程序跳到下一个 case,即使这个 case 的条件不成立
switch x := 2; x {
case 1:
    fmt.Println("第一种情况")
    fallthrough
case 2:
    fmt.Println("第二种情况")
    fallthrough
case 3:
    fmt.Println("第三种情况")
}

第二种情况
第三种情况

类型 switch

类型 switch 用于比较类型

go
var value interface{}
switch q := value.(type) {
case bool:
    fmt.Println("值是布尔型")
case float64:
    fmt.Println("值是float64类型")
case int:
    fmt.Println("值是int类型")
default:
    fmt.Printf("值的类型是: %T", q)
}

❤️ Select、deadlock 死锁