Conditional statements are fundamental constructs in programming languages that allow the execution of different code blocks based on certain conditions. In Go, conditional statements enable developers to control the flow of their programs based on the evaluation of expressions. This chapter aims to provide a comprehensive guide to conditional statements in Go, covering basic if-else statements to more advanced switch statements and conditional expressions.
The most basic form of conditional statement in Go is the if-else statement. It allows the execution of different code blocks based on whether a specified condition evaluates to true or false. Let’s explore basic if-else statements with examples:
package main
import "fmt"
func main() {
age := 20
if age >= 18 {
fmt.Println("You are an adult")
} else {
fmt.Println("You are a minor")
}
}
age
and assign it a value of 20.if
statement checks if the age
is greater than or equal to 18.In some cases, we may need to evaluate multiple conditions sequentially. We can achieve this using if-else if-else statements. Let’s see an example:
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 {
fmt.Println("Grade: D")
}
}
score
and assign it a value of 85.score
against different ranges to determine the grade.In some scenarios, we may need to nest conditional statements inside other conditional statements. This is known as nested if-else statements. Let’s illustrate this with an example:
package main
import "fmt"
func main() {
num := 10
if num > 0 {
if num%2 == 0 {
fmt.Println("Even number")
} else {
fmt.Println("Odd number")
}
} else {
fmt.Println("Number is zero or negative")
}
}
num
and assign it a value of 10.Switch statements provide a concise way to evaluate multiple conditions without the need for nested if-else statements. They are particularly useful when dealing with multiple possible values for a variable. Let’s see how switch statements work:
package main
import "fmt"
func main() {
day := "Monday"
switch day {
case "Monday":
fmt.Println("It's Monday")
case "Tuesday":
fmt.Println("It's Tuesday")
case "Wednesday", "Thursday":
fmt.Println("It's midweek")
case "Friday":
fmt.Println("It's Friday")
default:
fmt.Println("It's the weekend")
}
}
day
and assign it a value of “Monday”.day
and executes the corresponding case block.In this chapter, we covered conditional statements in Go, including basic if-else statements, if-else if-else statements, nested if-else statements, and switch statements. Conditional statements are essential for controlling the flow of a program based on different conditions. By mastering these concepts, you'll be able to write more flexible and efficient Go programs. Happy coding !❤️