if / else
In Go, the if statement does not require parentheses around the condition, but curly braces around the block are mandatory. You can also include an initialization statement before the condition.
Syntax
// Basic if
if condition {
// Executes when condition is true
}
// if-else
if condition {
// Executes when true
} else {
// Executes when false
}
// if-else if-else
if condition1 {
// Executes when condition1 is true
} else if condition2 {
// Executes when condition2 is true
} else {
// Executes when neither condition is true
}
// if with initialization statement (variable scope is limited to the if block)
if initStatement; condition {
// Variables declared in initStatement are only valid here
}
Sample Code
package main
import (
"fmt"
"strconv"
)
func grade(score int) string {
if score >= 90 {
return "A"
} else if score >= 70 {
return "B"
} else if score >= 50 {
return "C"
} else {
return "D"
}
}
func main() {
fmt.Println(grade(95)) // A
fmt.Println(grade(72)) // B
fmt.Println(grade(40)) // D
// if with initialization statement (idiomatic error handling pattern)
if n, err := strconv.Atoi("42"); err == nil {
fmt.Printf("Conversion succeeded: %d\n", n) // n is only valid here
} else {
fmt.Println("Conversion failed:", err)
}
// Example of a failed conversion
if n, err := strconv.Atoi("abc"); err == nil {
fmt.Println(n)
} else {
fmt.Println("Error:", err)
}
// Map value lookup with if (idiomatic pattern)
m := map[string]int{"alice": 100, "bob": 80}
if score, ok := m["alice"]; ok {
fmt.Println("alice's score:", score)
}
}
Notes
The if statement with an initialization (e.g., if v, err := f(); err == nil { ... }) is one of the most common patterns in Go. It lets you receive return values from a function and check a condition at the same time, while keeping the variable scope limited to the if block.
In Go, adding parentheses around the condition is not a syntax error, but gofmt (the official formatter) will automatically remove them. Follow Go's code style and write conditions without parentheses.
Go does not have a ternary operator (condition ? A : B). Assign values conditionally using a regular if-else statement instead. If you have many branches, consider using a switch statement for better readability.
If you find any errors or copyright issues, please contact us.