Go if-else Statements
Learn Go through interactive, bite-sized lessons. Build scalable applications with modern concurrency.
Start Go Journey →If-else statements in Go provide a powerful way to control the flow of your program based on specific conditions. They allow you to execute different blocks of code depending on whether a condition is true or false.
Basic Syntax
The basic syntax of an if-else statement in Go is as follows:
if condition {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
Go doesn't require parentheses around the condition, but the curly braces are mandatory.
Simple If Statement
Let's start with a simple if statement:
age := 18
if age >= 18 {
fmt.Println("You are an adult")
}
In this example, the message will be printed only if the age is 18 or greater.
If-Else Statement
Adding an else clause allows you to specify what happens when the condition is false:
if age >= 18 {
fmt.Println("You are an adult")
} else {
fmt.Println("You are a minor")
}
Multiple Conditions with Else If
For more complex logic, you can use else if to check multiple conditions:
score := 85
if score >= 90 {
fmt.Println("A grade")
} else if score >= 80 {
fmt.Println("B grade")
} else if score >= 70 {
fmt.Println("C grade")
} else {
fmt.Println("Failed")
}
Initialization Statement
Go allows you to include an initialization statement before the condition:
if num := 10; num%2 == 0 {
fmt.Println(num, "is even")
} else {
fmt.Println(num, "is odd")
}
The variable 'num' is scoped to the if-else block and isn't accessible outside it.
Best Practices
- Keep conditions simple and readable
- Use Go Switch Statements for multiple conditions on the same variable
- Avoid deep nesting of if-else statements
- Consider extracting complex conditions into separate functions for clarity
Error Handling
If-else statements are commonly used for error handling in Go:
if err := someFunction(); err != nil {
// handle the error
return err
}
// continue with normal execution
This pattern is idiomatic in Go and is used extensively for error handling.
Conclusion
If-else statements are fundamental to control flow in Go. They provide a straightforward way to make decisions in your code based on specific conditions. As you progress in Go programming, you'll find yourself using these statements frequently, often in combination with other control structures like Go For Loops and Switch Statements.