In this tutorial, we will learn about conditional statements in Go. We will cover the basics of using if, if-else, and switch statements to control the flow of a program based on conditions.
Conditional statements are used to perform different actions based on different conditions. Go supports several types of conditional statements: if
, if-else
, and switch
.
An if
statement in Go is used to execute a block of code only if a specified condition is true.
if condition {
// statements
}
An if-else
statement in Go 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 {
// statements
} else {
// statements
}
An if-else if-else
statement in Go is used to test multiple conditions and execute corresponding blocks of code.
if condition1 {
// statements
} else if condition2 {
// statements
} else {
// statements
}
A switch
statement in Go is used to execute one block of code among many options. It is an alternative to using multiple if-else if
statements.
switch expression {
case value1:
// statements
case value2:
// statements
default:
// statements
}
We can use an if statement in Go to execute a block of code only if a specified condition is true.
For example,
age
and assign it a value.if
statement to check if the value of age
is greater than or equal to 18.package main
import "fmt"
func main() {
age := 20
if age >= 18 {
fmt.Println("You are an adult.")
}
}
You are an adult.
We can use an if-else statement in Go to execute one block of code if a condition is true, and another block of code if the condition is false.
For example,
num
and assign it a value.if-else
statement to check if the value of num
is even or odd.package main
import "fmt"
func main() {
num := 7
if num%2 == 0 {
fmt.Println("The number is even.")
} else {
fmt.Println("The number is odd.")
}
}
The number is odd.
We can use an if-else if-else statement in Go to test multiple conditions and execute corresponding blocks of code.
For example,
score
and assign it a value.if-else if-else
statement to check the value of score
and print a grade based on the value.package main
import "fmt"
func main() {
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 if score >= 60 {
fmt.Println("Grade: D")
} else {
fmt.Println("Grade: F")
}
}
Grade: B
We can use a switch statement in Go to execute one block of code among many options.
For example,
day
and assign it a value.switch
statement to print the name of the day based on its value.package main
import "fmt"
func main() {
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Invalid day")
}
}
Wednesday