Flow Control
Flow control determines the path your code takes. This chapter covers how Go manages logic using loops, conditions, and deferred actions.
For#
Go has only one looping construct,the for loop,. The basic for loop has the three components seprated by semicolons: the init statement:executed before the first iteration the condition expression:evaluated before every iteration the post statement:executed at hte end of every iteration
The init statement will often be a short variable declaration,and the variables declared there are visible only in the scope of the for statement
The loop will stop iterating once the boolean condition evaluates to false.
Note:unlike other languages there are no parentheses surrounding the three components of the for statement and the curly braces are always required.
At that point you can drop the semicolons: C's while is spelled for in Go.
package main
import "fmt"
func main(){
sum := 1
for sum< 1000{
sum+=sum
}
fmt.Println(sum)
}
Switch#
Switch only runs the selected case, not all the cases that follow.
The break statement is provided automatically.
Switch cases need not be constants,and the values involved need not be integers.
Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
Switch without a condition is the same as switch true.
defer#
A defer statement defers the execution of a function until the surrounding function returns.The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
package main
import "fmt"
func main(){
defer fmt.Println("word")
fmt.Println("hello")
}
print: hello
word
func test(){
i := 0
defer fmt.Println("the i in defer:",i)
i=100
fmt.Println("the i in normal:",i)
}
print: the i in normal: 100 the i in defer: 0
Vocabulary List#
iteration:循环的语句
post statement:后置语句,循环里卸载最后,每次迭代结束才执行的那句,比如i++
optional:可选择的
compactly:简洁的
square root function:平方根函数
implement:实施,强调从无到有
execute:强调“按流程执行已有的东西”,运行代码/命令