🔁 Go Decision Making – if, else, switch & select with Examples
🧲 Introduction – Why Decision Making Matters in Go
Decision-making structures let your Go program respond to conditions—whether you’re validating input, handling multiple cases, or coordinating concurrent tasks. Go provides if, if...else, switch, and the powerful select statement to build responsive and safe logic flows.
🎯 In this guide, you’ll learn:
- How to use
if,if...else, and nestedifconditions - How
switchsimplifies multi-condition logic - How
selectis used for concurrent channel operations - Best practices for writing clean, readable conditionals
📘 Topics Covered
| 🔹 Statement | 📖 Purpose |
|---|---|
| ✅ Go If Statement | Execute a block when a condition is true |
| 🔁 Go If…Else Statement | Handle alternative paths when conditions are false |
| 🧱 Go Nested If Statements | Evaluate multiple levels of conditions |
| 🔀 Go Switch Statement | Handle multiple discrete values in a cleaner format |
| 🛰️ Go Select Statement | Wait on multiple channel operations (used in concurrency) |
✅ Go – If Statement
package main
import "fmt"
func main() {
age := 18
if age >= 18 {
fmt.Println("You are an adult.")
}
}
🧠 No parentheses are required around the condition, but curly braces {} are mandatory.
🔁 Go – If…Else Statement
package main
import "fmt"
func main() {
score := 65
if score >= 70 {
fmt.Println("Pass")
} else {
fmt.Println("Fail")
}
}
✅ You can chain more with else if:
if score >= 90 {
fmt.Println("A grade")
} else if score >= 75 {
fmt.Println("B grade")
} else {
fmt.Println("C grade")
}
🧱 Go – Nested If Statements
package main
import "fmt"
func main() {
age := 25
city := "Mumbai"
if age >= 18 {
if city == "Mumbai" {
fmt.Println("Eligible voter in Mumbai.")
}
}
}
🧠 Avoid too many nested ifs by combining logic:
if age >= 18 && city == "Mumbai" {
fmt.Println("Eligible voter in Mumbai.")
}
🔀 Go – Switch Statement
package main
import "fmt"
func main() {
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Another day")
}
}
✅ Key Features:
- No need for
break(automatic) - Use
fallthroughto force execution to next case - Works with strings, ints, or custom conditions
✨ Switch with Conditions
x := 25
switch {
case x < 0:
fmt.Println("Negative")
case x == 0:
fmt.Println("Zero")
case x > 0:
fmt.Println("Positive")
}
🛰️ Go – Select Statement (For Channels)
The select statement is like switch, but for concurrent channel operations:
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
ch1 <- "from ch1"
}()
go func() {
time.Sleep(2 * time.Second)
ch2 <- "from ch2"
}()
select {
case msg1 := <-ch1:
fmt.Println("Received:", msg1)
case msg2 := <-ch2:
fmt.Println("Received:", msg2)
default:
fmt.Println("No channel ready")
}
}
✅ Use select to wait for the first ready channel, making it ideal for building concurrent logic.
📌 Summary – Recap & Next Steps
Go’s decision-making tools allow you to build logic flows that are both clean and concurrent-safe. Whether you’re handling basic conditions or channel events, Go’s syntax stays minimal and efficient.
🔍 Key Takeaways:
- Use
iffor simple true/false checks if...elsehandles conditional branches- Avoid deep nesting using
else ifor logical operators switchsimplifies multi-value conditionsselecthandles concurrent communication elegantly
⚙️ Real-World Applications:
- Input validation and error handling
- User role access checks in APIs
- Channel selection in goroutine-driven code
❓ Frequently Asked Questions
❓ Does Go support ternary operators like ?:?
✅ ❌ No. Use standard if...else instead. Go avoids ternary for clarity.
❓ Can switch statements compare strings in Go?
✅ Yes! Example:
switch lang {
case "go": fmt.Println("Golang")
}
❓ What happens if no case matches in switch?
✅ The default block executes, just like in other languages.
❓ Can select be used without channels?
✅ ❌ No. select only works with channels.
❓ Is fallthrough required in Go’s switch cases?
✅ ❌ No. Go automatically breaks. Use fallthrough only if you want to continue to the next case.
Share Now :
