In Go, the if-else statement is used to execute different blocks of code based on whether a condition is true or false. It allows you to provide alternative code paths for different scenarios. Here’s the syntax of the if-else statement in Go:
if condition {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Here are a few examples of using the if-else statement in Go:
- Checking if a number is positive or negative:
num := -5
if num > 0 {
fmt.Println("The number is positive")
} else {
fmt.Println("The number is negative")
}
- Checking if a person is eligible to vote:
age := 17
if age >= 18 {
fmt.Println("You are eligible to vote")
} else {
fmt.Println("You are not eligible to vote")
}
- Checking if a number is even or odd:
num := 12
if num%2 == 0 {
fmt.Println("The number is even")
} else {
fmt.Println("The number is odd")
}
- Checking multiple conditions with else if:
score := 85
if score >= 90 {
fmt.Println("A")
} else if score >= 80 {
fmt.Println("B")
} else if score >= 70 {
fmt.Println("C")
} else {
fmt.Println("D")
}
The if-else statement allows you to choose between different code paths based on the outcome of a condition. It provides flexibility in handling different cases and making decisions in your Go programs.