for
In go there's no while
and instead for
without a condition will loop
repeatedly until you break out of the loop or return from the enclosing
function. You can also continue to the next iteration of the loop.
package main
import "fmt"
func main() {
// 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 := 7; j <= 9; j++ {
fmt.Println(j)
}
// `for` without a condition will loop repeatedly
// until you `break` out of the loop or `return` from
// the enclosing function.
for {
fmt.Println("loop")
break
}
// You can also `continue` to the next iteration of
// the loop.
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
// Finally, there's for range which is used to loop over
// maps or arrays (and thus strings). Using i, v is common
// for index and value. If you only need the value replace
// i with _. If you only need the index simply omit the , v.
for i, c := range "go" {
fmt.Println(i, c)
}
}
if/else
A statement can precede conditionals; any variables declared in this statement are available in all branches.
There's no ternary operator or other similar shortcuts.
package main
import "fmt"
func main() {
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}
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")
}
}
switch
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
without an
expression is an alternate way to express if/else logic. Here we also show how
the case expressions can be non-constants.
A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable t will have the type corresponding to its clause
package main
import (
"fmt"
"time"
)
func main() {
i := 2
fmt.Print("Write ", i, " as ")
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
whatAmI := func(i interface{}) {
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool")
case int:
fmt.Println("I'm an int")
default:
fmt.Printf("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}