Conditional statements allow your Go programs to make decisions and execute code blocks based on conditions.
The most basic conditional statement is if. It executes a block of code only if a specified condition is true.
if condition {
// code to execute when condition is true
}
Example:
age := 18
if age >= 18 {
fmt.Println("You are an adult.")
}
Use else to execute code when the if condition is false.
if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a minor.")
}
Use else if to check multiple conditions in sequence.
score := 85
if score >= 90 {
fmt.Println("Grade: A")
} else if score >= 80 {
fmt.Println("Grade: B")
} else if score >= 70 {
fmt.Println("Grade: C")
} else {
fmt.Println("Grade: F")
}
Go allows an optional short statement to execute before the condition in an if. Variables declared in this statement are scoped to the if block.
if err := someFunction(); err != nil {
fmt.Println("Error occurred:", err)
} else {
fmt.Println("Success")
}
The switch statement is a clean way to select one of many code blocks to execute.
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Invalid day")
}
() around conditions.{} are mandatory.switch, cases do not fall through by default. Use fallthrough to continue.if for simple conditions, if-else for two-way decisions, else if for multiple choices, and switch for clearer multi-case logic.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!