Go (or Golang, if you’re fancy) doesn’t just execute code blindly—it can think! Well, sort of. Using conditional statements like if
, else if
, else
, and switch
, you can make Go execute different actions based on different conditions. Basically, you’re teaching Go to make decisions like a true AI overlord (or just a very smart program).
The if
Statement (The Basic Decision-Maker)
Think of if
as Go’s way of saying, “Hey, if this is true, do this!”
package main
import "fmt"
func main() {
var temperature int = 30
if temperature > 25 {
fmt.Println("It's hot! Grab some ice cream!")
}
}
Output:
It's hot! Grab some ice cream!
If the temperature is greater than 25, Go prints the message. If not, it just stares at you silently.
The else
Statement (Go’s Backup Plan)
Sometimes, things don’t go as expected. That’s when else
comes in.
package main
import "fmt"
func main() {
var temperature int = 15
if temperature > 25 {
fmt.Println("It's hot! Grab some ice cream!")
} else {
fmt.Println("It's cold! Get a blanket!")
}
}
Output:
It's cold! Get a blanket!
If the first condition isn’t met, Go executes the else
block instead. No ice cream today.
The else if
Statement (For When You Need More Choices)
When life isn’t just black and white, else if
helps you add more conditions.
package main
import "fmt"
func main() {
var temperature int = 20
if temperature > 30 {
fmt.Println("It's boiling! Stay indoors!")
} else if temperature > 20 {
fmt.Println("Nice weather! Go for a walk!")
} else {
fmt.Println("It's chilly! Grab a coffee!")
}
}
Output:
Nice weather! Go for a walk!
Now, Go picks the condition that fits best. More choices, more fun!
The switch
Statement (Go’s Way of Avoiding a Million if
s)
If you find yourself writing too many if-else
conditions, switch
comes to the rescue!
package main
import "fmt"
func main() {
day := "Monday"
switch day {
case "Monday":
fmt.Println("Ugh, it's Monday again...")
case "Friday":
fmt.Println("TGIF!")
case "Sunday":
fmt.Println("Time to relax!")
default:
fmt.Println("Just another regular day!")
}
}
Output:
Ugh, it's Monday again...
switch
checks day
and runs the matching case. If no case matches, the default
case is executed.
Conditional statements help your Go programs make decisions like a boss! Whether you're using if
, else
, else if
, or switch
, you now have the tools to make Go smarter. Now, go forth and code wisely!
0 Comments