Go Conditional Statements
- In Go, conditions help control the flow of a program by allowing code to execute based on whether a condition evaluates to true or false.
Comparison Operators
Go supports standard comparison operators:
- < : Less than
- <= : Less than or equal to
- > : Greater than
- >= : Greater than or equal to
- == : Equal to
- != : Not equal to
Logical Operators
Logical operators are used to combine multiple conditions:
- && : Logical AND (true if both conditions are true)
- || : Logical OR (true if at least one condition is true)
- ! : Logical NOT (inverts the condition)
Examples of Conditions
x > y // true if x is greater than y
x != y // true if x is not equal to y
(x > y) && (y > z) // true if both conditions are true
(x == y) || z > 10 // true if x equals y OR z is greater than 10
Conditional Statements in Go
Go provides several ways to perform conditional execution:
1. if Statement
Executes a block if the condition is true.
Example:
if x > y {
fmt.Println("x is greater than y")
}
2. if...else Statement
Provides an alternative block if the condition is false.
Example:
if x > y {
fmt.Println("x is greater than y")
} else {
fmt.Println("x is not greater than y")
}
3. if...else if...else Statement
Allows checking multiple conditions in sequence.
Example:
if x > y {
fmt.Println("x is greater than y")
} else if x == y {
fmt.Println("x and y are equal")
} else {
fmt.Println("x is less than y")
}
4. switch Statement
Selects from multiple blocks based on the value of a variable.
Example:
switch day := 3; day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Another day")
}