if and else
marks := 72
if marks >= 75 {
fmt.Println("Distinction")
} else if marks >= 40 {
fmt.Println("Pass")
} else {
fmt.Println("Fail")
}
// if with a short statement
if n := len("hello"); n > 3 {
fmt.Println("long word")
}Go does not need parentheses around conditions, but braces are required.
for: the only loop
for i := 1; i <= 5; i++ { // classic
fmt.Println(i)
}
n := 3
for n > 0 { // like while
n--
}
for { // infinite loop
break
}range
fruits := []string{"mango", "banana", "apple"}
for index, fruit := range fruits {
fmt.Println(index, fruit)
}
for _, fruit := range fruits { // ignore the index with _
fmt.Println(fruit)
}switch
day := "Sat"
switch day {
case "Sat", "Sun":
fmt.Println("Weekend")
default:
fmt.Println("Weekday")
}
switch { // no expression: acts like if/else
case marks >= 75:
fmt.Println("A")
case marks >= 60:
fmt.Println("B")
}Go's switch does not fall through to the next case unless you write fallthrough.
defer
defer runs a call when the function ends. It is commonly used to close files.
defer fmt.Println("done")
fmt.Println("working")Practice
Print numbers from 1 to 30, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for both.