Introduction
Control structures in Go, such as if
, else
, and switch
, are used to make decisions and control the flow of your program. In this guide, we'll explore these control structures with sample code and explanations.
If and Else Statements
The if
statement is used to execute a block of code if a specified condition is true. Optionally, you can use an else
block to execute code when the condition is false. Here's an example:
package main
import "fmt"
func main() {
age := 30
if age < 18 {
fmt.Println("You are a minor.")
} else {
fmt.Println("You are an adult.")
}
}
In this code, the program checks if age
is less than 18. If the condition is true, it prints "You are a minor." Otherwise, it prints "You are an adult."
Else If Statements
You can use else if
statements to check multiple conditions sequentially. Here's an example:
package main
import "fmt"
func main() {
age := 25
if age < 18 {
fmt.Println("You are a minor.")
} else if age < 65 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a senior citizen.")
}
}
In this code, the program checks multiple conditions to determine whether you are a minor, an adult, or a senior citizen.
Switch Statement
The switch
statement allows you to evaluate an expression against multiple possible cases. Here's an example:
package main
import "fmt"
func main() {
day := "Monday"
switch day {
case "Monday":
fmt.Println("It's the start of the workweek.")
case "Friday":
fmt.Println("It's almost the weekend!")
default:
fmt.Println("It's another day.")
}
}
In this code, the program evaluates the value of day
and prints a message based on the case that matches.
Further Resources
To dive deeper into Go control structures, explore the following resources:
- Go Tour - Control Structures - An interactive online tutorial for learning Go control structures.
- Effective Go - Control Structures - Official Go documentation on control structures.