If
/* general syntax */
if <condition-1> {
<then-block-1>
} else if <condition-2> {
<then-block-2>
} else {
<then-block-3>
}
/* Scoping a variable to an if statement */
if n:=rand.Intn(10); n==0 {
fmt.Println("is 0")
} else if n>5 {
fmt.Println(">5")
} else {
fmt.Println("<5")
}
fmt.Println(n) // undefined
For Loop
/* c-style */
for i:=0; i<10; i++ {}
/* condition-only */
i:=1
for i<100 { i*= 2 }
/* infinite */
for {}
/* break and continue */
for { if i>100 {break}}
/* for-range with index */
evenVals:=[]int{2,4,6,8,10}
for index, value := range evenVals {}
/* for-range without index */
evenVals:=[]int{2,4,6,8,10}
for _, value := range evenVals {}
// for-range value is actually a copy, modifying it won't modify the actual array/map/string
Switch
/* syntax */
switch character {
case a, e, i, o, u:
fmt.Println("it's a vowel");
fmt.Println("that's it")
default:
fmt.Println("it's a consonant")
fmt.Println("please try again")
}
/* missing label: without a label, switch case be used as if-else */
switch {
case i%2 == 0:
fmt.Println("even")
case i%3 == 0:
fmt.Println("divisible by 3 and not by 2")
case i%7 ==0:
fmt.Println("divisible by 7 and neither by 2 nor 3")
default:
fmt.Println("not what i wanted")
}
Goto
Go forbids jumps that skip over variable declarations and jumps that go
into an inner or parallel block.
func main() {
a := 10
goto skip // illegal
b := 20
skip:
c := 30
fmt.Println(a, b, c)
if c > a {
goto inner // illegal
}
if a < b {
inner:
fmt.Println("a is less than b")
}
}