Loops & Conditional Statements
For Loop
for
is Go’s only looping construct. Here are some basic types of for loops.
The most basic type, with a single condition.
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
A classic initial/condition/after for loop.
for j := 0; j < 3; j++ {
fmt.Println(j)
}
Another way of accomplishing the basic “do this N times” iteration is range over an integer.
for i := range 3 {
fmt.Println("range", i)
}
You can also continue to the next iteration of the loop.
for n := range 6 {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
Conditional Statements
If-Else
Branching with if and else in Go is straight-forward. No need of brackets for if unlike other languages
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
A statement can precede conditionals; any variables declared in this statement are available in the current and all subsequent branches.
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
There is no ternary if in Go, so you’ll need to use a full if statement even for basic conditions.
Switch
Switch statements express conditionals across many branches.
i := 2
fmt.Print("Write ", i, " as ")
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}