This tutorial aims to give you a clear understanding of how to control the flow of a Go program. We will be focusing on conditional statements (if, if-else, switch) and loops (for, while). By the end of this tutorial, you will be able to write and understand Go programs that feature complex control flow.
You will learn:
Prerequisites:
In Go, we use conditional statements to make decisions based on certain conditions.
The if
statement is used to test a condition. If the condition is true, the block of code inside the if statement will be executed.
if condition {
// code to be executed if condition is true
}
The if-else
statement is used when you want to perform a different operation in the case where the initial if
condition is not met.
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
The switch
statement is used to select one of many blocks of code to be executed.
switch condition {
case n:
// code to be executed if condition = n
default:
// code to be executed if no case matches
}
Loops are used when we want to repeat a block of code multiple times.
In Go, the for
loop is the only loop statement. It can be used in three forms.
for condition {
// code to be executed while condition is true
}
for initialization; condition; post {
// code to be executed while condition is true
}
for {
// code to be executed infinitely
}
package main
import "fmt"
func main() {
age := 18
if age >= 18 {
fmt.Println("You are eligible to vote.")
} else {
fmt.Println("You are not eligible to vote.")
}
}
This code will output "You are eligible to vote." since the age variable is 18, which is greater than or equal to 18.
package main
import "fmt"
func main() {
day := "Friday"
switch day {
case "Monday":
fmt.Println("Today is Monday.")
case "Tuesday":
fmt.Println("Today is Tuesday.")
case "Friday":
fmt.Println("Today is Friday.")
default:
fmt.Println("Invalid day.")
}
}
This code will output "Today is Friday." since the day variable matches the "Friday" case.
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
This code will output the numbers from 0 to 4 in the console.
We have covered how to use conditional statements and loops in Go. You should now feel confident in controlling the flow of a Go program. For further learning, you could try implementing nested if-else statements and nested loops.
Take your time to work on these exercises. They will help solidify your understanding of control flow in Go. Happy coding!