How to Use If Else in Go: Simple Guide with Examples
if to run code when a condition is true, and else to run code when it is false. The syntax is simple: start with if condition { }, and optionally add else { } after it.Syntax
The if statement checks a condition (parentheses are not used in Go) and runs the code block if true. The else block runs if the if condition is false. You can also use else if to check multiple conditions.
- if condition { }: Runs code if condition is true.
- else { }: Runs code if previous
iforelse ifconditions are false. - else if condition { }: Checks another condition if the first
ifis false.
if condition { // code runs if condition is true } else if anotherCondition { // code runs if anotherCondition is true } else { // code runs if none of the above conditions are true }
Example
This example shows how to check a number and print if it is positive, negative, or zero using if, else if, and else.
package main import "fmt" func main() { number := 5 if number > 0 { fmt.Println("The number is positive.") } else if number < 0 { fmt.Println("The number is negative.") } else { fmt.Println("The number is zero.") } }
Common Pitfalls
Common mistakes include forgetting the curly braces { }, omitting the condition, or using parentheses around the condition (which are not used in Go). Also, Go requires the condition to be a boolean expression.
Another pitfall is not using else if properly and instead writing multiple separate if statements, which can cause all conditions to be checked instead of stopping at the first true one.
package main import "fmt" func main() { x := 10 // Wrong: missing braces // if x > 5 // fmt.Println("x is greater than 5") // Correct: if x > 5 { fmt.Println("x is greater than 5") } // Wrong: multiple ifs instead of else if if x > 0 { fmt.Println("x is positive") } if x > 5 { fmt.Println("x is greater than 5") } // Correct: if x > 0 { fmt.Println("x is positive") } else if x > 5 { fmt.Println("x is greater than 5") } }
Quick Reference
Remember these tips when using if else in Go:
- Curly braces
{ }are required even for single statements. - Conditions must be boolean expressions (true or false).
- Parentheses around conditions are not used in Go.
- Use
else ifto chain multiple conditions. - Indent code inside blocks for readability.
Key Takeaways
if to run code when a condition is true and else for the false case.{ } around the code blocks.else if to check multiple conditions in order.if statements when else if is more appropriate.