Control Flow: Conditionals and Loops
Explore control flow statements like `if`, `else`, `else if`, `for`, and `range` to control the execution of your Go programs.
Go Language Basics: Control Flow
Introduction to Control Flow
Control flow in programming refers to the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. It's the mechanism that allows your program to make decisions and repeat actions based on certain conditions. In Go, control flow is primarily managed through conditional statements and loops.
Conditionals: Making Decisions with if
, else
, and else if
Conditional statements allow you to execute different blocks of code based on whether a certain condition is true or false.
The if
Statement
The if
statement executes a block of code only if the specified condition is true. Note that in Go, there are no parentheses around the condition like you might see in C, Java, or JavaScript. The curly braces {}
are required.
package main
import "fmt"
func main() {
age := 25
if age >= 18 {
fmt.Println("You are an adult.")
}
}
The else
Statement
The else
statement provides an alternative block of code to execute if the if
condition is false.
package main
import "fmt"
func main() {
age := 15
if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a minor.")
}
}
The else if
Statement
The else if
statement allows you to chain multiple conditions together. It's used when you have more than two possible outcomes.
package main
import "fmt"
func main() {
score := 85
if score >= 90 {
fmt.Println("Grade: A")
} else if score >= 80 {
fmt.Println("Grade: B")
} else if score >= 70 {
fmt.Println("Grade: C")
} else if score >= 60 {
fmt.Println("Grade: D")
} else {
fmt.Println("Grade: F")
}
}
Shorthand if
with Initialization
Go allows you to declare and initialize variables within the if
condition itself. The scope of these variables is limited to the if
block (including the else if
and else
blocks). This is useful for concisely handling errors returned by functions.
package main
import (
"fmt"
"strconv"
)
func main() {
str := "123"
if num, err := strconv.Atoi(str); err == nil {
fmt.Println("Parsed number:", num)
} else {
fmt.Println("Error parsing string:", err)
}
}
Loops: Repeating Actions with for
and range
Loops allow you to execute a block of code repeatedly. Go has only one looping construct: the for
loop, but it's versatile enough to handle different looping scenarios.
The for
Loop
The for
loop has three parts: an initialization statement, a condition, and a post statement. All three parts are optional.
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println("Iteration:", i)
}
}
The for
Loop as a while
Loop
If you omit the initialization and post statements, the for
loop behaves like a while
loop. You simply provide a condition.
package main
import "fmt"
func main() {
i := 0
for i < 5 {
fmt.Println("Iteration:", i)
i++
}
}
The Infinite for
Loop
If you omit all three parts (initialization, condition, and post statement), you create an infinite loop. You'll typically use a break
statement inside the loop to exit it based on a condition.
package main
import "fmt"
func main() {
i := 0
for {
fmt.Println("Iteration:", i)
i++
if i > 5 {
break
}
}
}
The range
Keyword
The range
keyword is used to iterate over elements in various data structures like arrays, slices, strings, maps, and channels. It provides both the index (or key) and the value of each element.
Iterating over an Array/Slice
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30, 40, 50}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
// If you only need the value, you can discard the index using the blank identifier (_)
for _, value := range numbers {
fmt.Println("Value:", value)
}
}
Iterating over a String
package main
import "fmt"
func main() {
message := "Hello, Go!"
for index, runeValue := range message {
fmt.Printf("Index: %d, Rune: %c\n", index, runeValue)
}
}
Iterating over a Map
package main
import "fmt"
func main() {
studentGrades := map[string]int{
"Alice": 95,
"Bob": 80,
"Charlie": 75,
}
for name, grade := range studentGrades {
fmt.Printf("Name: %s, Grade: %d\n", name, grade)
}
}