This blog describes Conditional Statements in Go.
Conditional statements in Go allow you to control the flow of your program based on certain conditions. Go supports the typical conditional constructs found in many programming languages, such as if
, else if
, else
, and switch
statements. Here’s how each of these works in Go.
if
Statement
The if
statement is used to execute a block of code if a specified condition is true.
if condition {
// code to execute if condition is true
}
For Example.
age := 20
if age >= 18 {
fmt.Println("You are an adult.")
}
if
–else
Statement
The if
–else
statement is used to execute one block of code if the condition is true, and another block of code if the condition is false.
if condition {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
For example.
age := 16
if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a minor.")
}
if
–else if
–else
Statement
The if
–else if
–else
statement is used when you have multiple conditions to check.
if condition1 {
// code to execute if condition1 is true
} else if condition2 {
// code to execute if condition2 is true
} else {
// code to execute if all conditions are false
}
For example.
score := 75
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: D")
}
switch
Statement
The switch
statement evaluates an expression and matches it against a list of possible cases. It’s a cleaner way to write multiple if
–else if
statements.
switch expression {
case value1:
// code to execute if expression == value1
case value2:
// code to execute if expression == value2
default:
// code to execute if expression doesn't match any case
}
For example.
day := "Wednesday"
switch day {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
fmt.Println("Weekday")
case "Saturday", "Sunday":
fmt.Println("Weekend")
default:
fmt.Println("Invalid day")
}
These are the basic conditional statements in Go. They provide a way to make decisions in your programs based on various conditions.
Further Reading
Variables and Data Types in Go
Go Programming Practice Exercise
Program Structure in Go Programming Language
Spring Framework Practice Problems and Their Solutions
How to Create and Run a Simple Program in Go?
20+ Interview Questions on Go Programming Language
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language