-
For
- No parentheses and the
{}
are always required.
for i:=0; i<10; i++ {
sum +=i
} - The init and post statements are optional
sum :=1
for ; sum < 1000; {
sum +=sum
} - For is Go's "while". You can drop the semicolons from above which will change to
for sum < 1000 {
sum +=sum
}
just like the "while" in c. - Forever
for{
}
-
If
- No parentheses and the
{}
are always required.
if x < 0 {
} - Short statements: to execute before the condition.
if v := 1 ; v<10 {
return v
}- variables declared by short statement are only in the scope until the end of if(including else).
- Switch
switch os:=runtime.GOOS; os {
case "linux":
fmt.pritln(xxx)
....
default:
...
}- The evaluation is from top to bottom, and stop once one of the condition is true.
- switch with no condition is the same as
switch true
-
Defer
Defer funcs are pushed into a stack and executed in a last in first out order when the surrounding function returns.
func main() {
fmt.Println("counting")for i := 0; i < 10; i++ { defer fmt.Println(i) } fmt.Println("done") }
output:
counting
done
9
8
...