Go Conditions
Making decisions in your Go programs
🔀 What are Go Conditions?
Go conditions allow your program to make decisions and execute different code blocks based on whether certain conditions are true or false, enabling dynamic program behavior.
// Simple condition example
age := 18
if age >= 18 {
fmt.Println("You are an adult!")
}
Output:
You are an adult!
Types of Conditions
If Statement
Execute code when condition is true
if x > 0 {
fmt.Println("Positive")
}
If-Else
Handle both true and false cases
if x > 0 {
fmt.Println("Positive")
} else {
fmt.Println("Not positive")
}
Else If
Chain multiple conditions together
if x > 0 {
fmt.Println("Positive")
} else if x < 0 {
fmt.Println("Negative")
} else {
fmt.Println("Zero")
}
Short Statement
Declare and check in one line
if num := 10; num > 5 {
fmt.Println("Greater than 5")
}
🔹 Basic If Statement
The simplest form of condition in Go:
package main
import "fmt"
func main() {
temperature := 25
if temperature > 20 {
fmt.Println("It's warm outside!")
}
fmt.Println("Program continues...")
}
Output:
It's warm outside!
Program continues...
🔹 If-Else Statement
Handle both true and false conditions:
package main
import "fmt"
func main() {
score := 85
if score >= 90 {
fmt.Println("Excellent! Grade: A")
} else {
fmt.Println("Good job! Grade: B")
}
}
Output:
Good job! Grade: B
🔹 Multiple Conditions (Else If)
Chain multiple conditions for complex logic:
package main
import "fmt"
func main() {
grade := 78
if grade >= 90 {
fmt.Println("Grade: A")
} else if grade >= 80 {
fmt.Println("Grade: B")
} else if grade >= 70 {
fmt.Println("Grade: C")
} else {
fmt.Println("Grade: F")
}
}
Output:
Grade: C
🔹 Logical Operators
Combine multiple conditions using logical operators:
package main
import "fmt"
func main() {
age := 25
hasLicense := true
// AND operator (&&)
if age >= 18 && hasLicense {
fmt.Println("Can drive!")
}
// OR operator (||)
if age < 16 || !hasLicense {
fmt.Println("Cannot drive")
} else {
fmt.Println("Eligible to drive")
}
}
Output:
Can drive!
Eligible to drive
🔹 Short Variable Declaration
Declare and use variables within if statements:
package main
import "fmt"
func main() {
// Variable 'result' is only available within if block
if result := 10 * 5; result > 40 {
fmt.Printf("Result %d is greater than 40\n", result)
}
// result is not accessible here
fmt.Println("Outside if block")
}
Output:
Result 50 is greater than 40
Outside if block