?? Mastering Control Structures in Go: A Comprehensive Guide
Control structures are essential in programming, directing the flow of execution based on conditions and loops. In this post, we’ll break down the key control structures in Go—if, switch, for, and the unique defer, panic, and recover mechanisms.
?? If Statements
The if statement checks a condition and executes code if it's true.
number := 10
if number > 5 {
fmt.Println("The number is greater than 5")
} else {
fmt.Println("The number is 5 or less")
}
You can even initialize variables in the condition:
if number := 10; number > 5 {
fmt.Println("Greater than 5")
}
?? Switch Statements
switch allows more readable multi-way branching compared to multiple if-else.
switch day {
case "Monday":
fmt.Println("Start of the work week")
case "Friday":
fmt.Println("Almost the weekend")
default:
fmt.Println("Midweek")
}
Handle multiple cases at once:
switch day {
case "Monday", "Tuesday", "Wednesday", "Thursday":
fmt.Println("Weekday")
case "Saturday", "Sunday":
fmt.Println("Weekend")
}
?? For Loops
Go’s for loop is versatile—it’s the only loop structure but can handle various scenarios.
for i := 0; i < 5; i++ {
fmt.Println(i)
}
As a while loop:
领英推荐
i := 0
for i < 5 {
fmt.Println(i)
i++
}
Infinite loop:
for {
fmt.Println("Loop forever")
break // to exit
}
Use for range to iterate over collections:
numbers := []int{1, 2, 3}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
?? Defer, Panic, and Recover
fmt.Println("Start")
defer fmt.Println("End")
fmt.Println("Middle")
panic("Something went wrong!")
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from:", r)
}
}()
panic("Something went wrong!")
?? Conclusion
Understanding Go's control structures—if, switch, for, along with defer, panic, and recover—helps in writing cleaner, more efficient code. Master these tools, and you’ll be well on your way to writing better Go programs! ??