40

A Tour of Go: Basics 2

 5 years ago
source link: https://studygolang.com/articles/15302?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

For

For语句有三个基本部分组成,以分号隔开:

  • 初始语句:只在第一次循环开始前执行,通常就是变量定义和初始化,这里定义的变量作用范围只在For循环本身。
  • 条件表达式:每一次循环开始前执行,当false结束循环。
  • post语句:每一次循环结束后执行。

技巧:

  • 初始语句和post语句是可以省略的。
  • 条件表达式也可以省略,就是死循环。
  • Go语言只有一个循环结构,就是for语句。while语句在Go中也是由for表示。
// for
sum := 1
for ; sum < 1000; {
    sum += sum
}

// while
sum := 1
for sum < 1000 {
    sum += sum
}

注意点:

  • 与其他语言不同,三个语句不需要用括号括起来。
  • 循环体需要用大括号括起来。

If

跟for一样,if语句可以包含一个初始语句,作用范围限于if本身(包括else)。同样地,if语句也不需要小括号,但是需要大括号。

Switch

Switch是if else语句在某些场景下的更好选择。匹配到等于condition的case并执行,然后停止switch,不需要显式break。

同样可以有初始语句。

条件可以为空,表示switch true。

Defer

推迟到周围函数都执行完以后再执行。

被推迟的函数是放在stack里的,因此遵循后进先出原则。

应用场景比如用于清理动作等,参见: https://blog.golang.org/defer-panic-and-recover


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK