If-Else Statements in Go
This is where your programs start making decisions. Let's teach your code to think.
Also available on YouTube • 10:53 watch time
Making Decisions in Code
Up until now, every line of your program runs no matter what. But real programs need to make choices. Should the user see a welcome message or an error? Is the password correct? Is the item in stock? That's what if-else is for — it lets your code take different paths depending on a condition.
The Basic If Statement
The simplest form: "if this is true, do this."
age := 20
if age >= 18 {
fmt.Println("You are an adult.")
}
If age is 18 or more, the message prints. If not, nothing happens. Simple as that.
Adding an Else
What if you want to handle the "otherwise" case too?
score := 45
if score >= 50 {
fmt.Println("You passed!")
} else {
fmt.Println("You failed. Try again.")
}
Now your program responds either way. There's always an outcome.
Chaining with Else-If
When you have more than two possibilities:
marks := 85
if marks >= 90 {
fmt.Println("Grade: A")
} else if marks >= 75 {
fmt.Println("Grade: B")
} else if marks >= 60 {
fmt.Println("Grade: C")
} else {
fmt.Println("Grade: F")
}
Go checks each condition from top to bottom. The moment it finds one that's true, it runs that block and skips the rest. Order matters.
Go quirk: Unlike some languages, Go does not need parentheses around the condition. Writing if (age > 18) works, but the Go community convention is to drop them: if age > 18. Keep it clean.
Init Statements — A Go Superpower
Go lets you declare a variable right inside the if statement. That variable only exists within the if-else block:
if length := len("Golang"); length > 3 {
fmt.Println("That's a long word!")
}
// 'length' does not exist out here
This is surprisingly useful. It keeps temporary variables out of the wider scope and makes your code tidier.
Try It Yourself
Write a program that asks for a temperature value (you can hardcode it for now). Print "Cold" if it's below 15, "Warm" if it's between 15 and 30, and "Hot" if it's above 30.