在 Go 语言中,控制结构允许你控制代码的执行流程。主要的控制结构有 ifforswitch 和 select

if 语句

if 语句用于进行条件判断。基本语法如下:

if condition {
    // 代码块1
} else if condition {
    // 代码块2
} else {
    // 代码块3
}

例如:

score := 85
if score > 90 {
    fmt.Println("优秀")
} else if score > 60 {
    fmt.Println("合格")
} else {
    fmt.Println("不合格")
}

for 语句

for 语句用于进行循环。基本语法如下:

for initialization; condition; post {
    // 代码块
}

例如:

for i := 0; i < 10; i++ {
    fmt.Println(i)
}

你也可以使用 for 来创建一个无限循环:

for {
    fmt.Println("无限循环")
}

for 还可以用于遍历数组、切片、字典或通道(channel)等数据结构。

switch 语句

switch 语句用于多条件判断。基本语法如下:

switch initialization; condition {
case value1:
    // 代码块1
case value2:
    // 代码块2
default:
    // 默认代码块
}

例如:

dayOfWeek := 5
switch dayOfWeek {
case 1, 2, 3, 4, 5:
    fmt.Println("工作日")
case 6, 7:
    fmt.Println("周末")
default:
    fmt.Println("无效的日期")
}

select 语句

select 语句用于多通道选择操作,通常与 goroutine 和 channel 一起使用来实现并发编程。基本语法如下:

select {
case operation1:
    // 代码块1
case operation2:
    // 代码块2
default:
    // 默认代码块
}

例如:

select {
case msg1 := <-ch1:
    fmt.Println("Received", msg1)
case msg2 := <-ch2:
    fmt.Println("Received", msg2)
default:
    fmt.Println("No message received")
}

以上就是 Go 语言中的主要控制结构。理解并熟练掌握这些控制结构,是编写 Go 语言程序的基本技能。
推荐阅读:

https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA

https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

file


移动安全星球
1 声望2 粉丝