Control flow statements are one of the major concepts in programming because they allow you to build flexible and dynamic applications. They are so important that all programming languages feature them in one way or another, and Go is no exception.
In the previous article, you learned about variables, different types of variable declarations, data types, operators, the different sets of operators, and what they are used for in Go. In this article, we will explore how to use control flow statements and loops in Go.
Control Flow in Go
Control flow, also known as the flow of execution, is the order in which your program is executed. In Go, the application starts executing from the main
function inside the main.go
file, which is the application starting point. Consider the following code:
package main
import (
"fmt"
)
var name, surname string = "John", "Doe"
var uniName, major string = "The University of California", "Computer Science"
func main() {
isStudent := true
accessToUniAid := false
fmt.Println(accessToUniAid, isStudent)
fmt.Print("\n")
fmt.Println("Mr.", name, surname, "is a student and he is studying", major, "at", uniName, "He is a student and has access to the university financial aid")
fmt.Print("\n")
fmt.Println("Mr.", name, surname, "is not a student and he is not studying", "at", uniName, "Therefore he doesn't have access to the university financial aid")
}
The code above will execute in the following order:
Declare the file as part of the
main
package.Import the
fmt
package.Declare
name
andsurname
variables.Declare
uniName
andmajor
variables.Run the
main
function and:Declare
isStudent
andaccessToUniAid
variables.Print the values of
isStudent
andaccessToUniAid
.Print an empty line.
Print
"Mr. John Doe is a student, and he is studying Computer Science at the University of California. He is a student and has access to the university financial aid"
.Print an empty line.
Print
"Mr. John Doe is not a student, and he is not studying at the University of California. Therefore, he doesn't have access to the university financial aid
.
While this is exactly how it should run, this is not an ideal way to write programs because users will see messages that are not relevant to them, and that would definitely confuse them.
Go provides a way for you to manipulate the control flow of your application so it can interact with users in the most relatable and efficient way possible using the if-else
statements.
How to use if-else
Statement in Go
if-else
statements in Go are used to tweak the flow of execution so your applications can work predictably. For example, the previous code block was supposed to print just one of the statements based on who the user is; edit the main
function to look like this:
func main() {
isStudent := true
accessToUniAid := true
fmt.Println(accessToUniAid, isStudent)
if isStudent && accessToUniAid {
fmt.Println("Mr.", name, surname, "is a student and he is studying", major, "at", uniName, "He is a student and has access to the university financial aid")
} else {
fmt.Println("Mr.", name, surname, "is not a student and he is not studying", "at", uniName, "Therefore he doesn't have access to the university financial aid")
}
}
The code above is the same as the previous code block, but this time, I used the if-else
and the &&
logical operator that you learned in the previous article to check if the user is a student and has access to the university's aid and then prints a response based on the result of the expression. The code inside the correct if
block curly braces {}
will be printed to the user and skip the remaining checks.
The else if
Block
Go allows you to make additional checks between the if
and the else
blocks to make your applications even more flexible. For example, if the user is a student but doesn't have access to the university's aid, and you want to give a response that shows them how to get access, you can do that like so:
func main() {
isStudent := false
accessToUniAid := false
fmt.Println(accessToUniAid, isStudent)
if isStudent && accessToUniAid {
fmt.Println("Mr.", name, surname, "is a student and he is studying", major, "at", uniName, "He is a student and has access to the university financial aid")
} else if isStudent && !accessToUniAid {
fmt.Println("Mr.", name, surname, "is a student and he is studying", major, "at", uniName, "He is a student but doesn't have access to the university financial aid. He can check if he is eligible for the financial aid by visiting the Eligibility page on the university website")
} else {
fmt.Println("Mr.", name, surname, "is not a student and he is not studying", "at", uniName, "Therefore he doesn't have access to the university financial aid")
}
}
The code above is the same as the previous code block but this time, I used the else if
and the !
logical operator that you learned in the previous article to add an additional check that sees if the user is a student but doesn't have access to the university's aid and then it prints a response based on the result of the expression.
Now, the execution flow of your program depends on the value of accessToUniAid
and isStudent
variables and will execute like this:
Declare the file as part of the
main
package.Import the
fmt
package.Declare
name
andsurname
variables.Declare
uniName
andmajor
variables.Run the
main
function and:Declare
isStudent
andaccessToUniAid
variables.Print the values of
isStudent
andaccessToUniAid
.Checks if
accessToUniAid
andisStudent
variables are true. If yes, it then prints"Mr. John Doe is a student and he is studying Computer Science at the University of California. He is a student and has access to the university financial aid"
and exits the program. If no, it continues the execution.Checks if
isStudent
is true andaccessToUniAid
is false. If yes, it then prints"Mr. John Doe is a student and he is studying Computer Science at the University of California He is a student but doesn't have access to the university financial aid. He can check if he is eligible for the financial aid by visiting the Eligibility page on the university website"
and exits the program. If no, it continues the execution.If the program gets to this part, it means
accessToUniAid
andisStudent
variables are both false, so it prints"Mr. John Doe is not a student and he is not studying at University of California Therefore he doesn't have access to the university financial aid
.
Your application can now give the user a response based on their status. Play around with the values of accessToUniAid
and isStudent
variables to see what response you get.
Note: You can add as many
else if
blocks as possible between yourif
andelse
blocks.
Shorthand if-else
Block
You can use a shorthand variable declaration with an if-else
block like this:
func main() {
if isStudent, accessToUniAid := true, true; isStudent && accessToUniAid {
fmt.Println("Mr.", name, surname, "is a student and he is studying", major, "at", uniName, "He is a student and has access to the university financial aid")
} else if isStudent && !accessToUniAid {
fmt.Println("Mr.", name, surname, "is a student and he is studying", major, "at", uniName, "He is a student but doesn't have access to the university financial aid. He can check if he is eligible for the financial aid by visiting the Eligibility page on the university website")
} else {
fmt.Println("Mr.", name, surname, "is not a student and he is not studying", "at", uniName, "Therefore he doesn't have access to the university financial aid")
}
}
The code above works the same way as the previous code block but with the shorthand variable declaration.
Note: When using the shorthand syntax, the
accessToUniAid
andisStudent
variables are only available in theif-else
block of code, which means they won't be available for use after the execution of theif
block.
Next, let's see how to use the switch
statement in the next section.
The switch
Statement in Go
Go provides the switch
statement as an alternative to the if-else
statements in cases where you have multiple else if
blocks or complex if-else
statements. For example, if you want to send a different response to the user based on what day it is, add the following code to your main
function:
dayOfWeek := "Sunday"
switch dayOfWeek {
case "Monday":
fmt.Println("It's Monday, time to start the week!")
case "Tuesday":
fmt.Println("It's Tuesday, already two days down.")
case "Wednesday":
fmt.Println("It's Wednesday, halfway through the week!")
case "Thursday":
fmt.Println("It's Thursday, one more day to go.")
case "Friday":
fmt.Println("It's Friday, time to celebrate!")
case "Saturday":
fmt.Println("It's Saturday, weekend is here!")
case "Sunday":
fmt.Println("It's Sunday, time to relax.")
}
The code above defines a dayOfWeek
variable and uses a switch
statement to check what day of the week it is and prints a response based on that.
Checking Multiple Cases in Go
Sometimes, you might want to check multiple values and return a response based on that. Using the previous example, if you want to check if the days are correct in either English or Spanish, you can do so with a comma (,
) like so:
dayOfWeek := "Miércoles"
switch dayOfWeek {
case "Monday", "Lunes":
fmt.Println("It's", dayOfWeek, "time to start the week!")
case "Tuesday", "Martes":
fmt.Println("It's", dayOfWeek, "already two days down.")
case "Wednesday", "Miércoles":
fmt.Println("It's", dayOfWeek, " halfway through the week!")
case "Thursday", "Jueves":
fmt.Println("It's", dayOfWeek, "one more day to go.")
case "Friday", "Viernes":
fmt.Println("It's", dayOfWeek, "time to celebrate!")
case "Saturday", "Sábado":
fmt.Println("It's", dayOfWeek, "weekend is here!")
case "Sunday", "Domingo":
fmt.Println("It's", dayOfWeek, "time to relax.")
}
The code above does the same as the previous code block, but this time, it also checks if the day is written in Spanish and responds accordingly.
The default
Case
Go allows you to add a default
case to the end of your cases to respond to any value you didn't specify a case for. For example, the above code will not print anything if the user mistakenly gives it a value of "Tuesdays"
, which would confuse the user because they won't know what went wrong. However, you can fix that with a default
case like this:
dayOfWeek := "Miércoless"
switch dayOfWeek {
case "Monday", "Lunes":
fmt.Println("It's", dayOfWeek, "time to start the week!")
case "Tuesday", "Martes":
fmt.Println("It's", dayOfWeek, "already two days down.")
case "Wednesday", "Miércoles":
fmt.Println("It's", dayOfWeek, " halfway through the week!")
case "Thursday", "Jueves":
fmt.Println("It's", dayOfWeek, "one more day to go.")
case "Friday", "Viernes":
fmt.Println("It's", dayOfWeek, "time to celebrate!")
case "Saturday", "Sábado":
fmt.Println("It's", dayOfWeek, "weekend is here!")
case "Sunday", "Domingo":
fmt.Println("It's", dayOfWeek, "time to relax.")
default:
fmt.Println(dayOfWeek, "is not a valid day of the week.")
}
The code above does the same as the previous code block, but this time, I added a default case that prints a response if the value is not a valid day of the week in both English and Spanish.
Loops in Go
A loop in programming is a way to perform a particular task multiple times, usually based on a condition. Unlike other programming languages, Go has only one loop method which is the for
loop.
How to Use The for
Loop in Go
A basic for
loop in Go will look like so:
for count := 0; count < 5; count++ {
fmt.Println(count)
}
The code above will print 0 1 2 3 4
and exit the program. The first part of the loop is variable initialization. In this case, count
; the second part is a condition that checks if count
is less than 5; the third part is the post that adds 1 to the value of count
, and finally, the print statement inside the curly brace will print the value of count
every time the condition returns true
.
Also, the count
variable is only available inside the loop and will be discarded once the loop finish running. However, you can declare the variable outside of the loop like so:
count := 0
for count < 5 {
count++
fmt.Println(count)
}
The code above is the same as the previous block but will print 1 2 3 4 5
because I now have the count++
that adds 1 to the value of count
inside the curly braces before printing its value.
The break
Keyword
Go allows you to stop a loop based on a condition using the break
statement like so:
count := 0
for count < 5 {
count++
fmt.Println(count)
if count >= 3 {
break
}
}
The code above is the same as the previous block but will print 1 2 3
because I now have a break
statement once the value of count
is greater than or equal to 3.
The continue
Keyword
You guessed it! The continue
keyword is used to continue the loop after doing something inside the loop like so:
for count := 0; count <= 10; count++ {
if count == 3 {
fmt.Println("Third time is the charm")
continue
}
fmt.Println("count is", count)
}
The code above is the same as the previous block but will print "Third time is the charm"
when the value of count
is equal to 3 before continuing the loop.
Nested Loops in Go
Go allows you to nest loops by simply putting another loop inside a loop like so:
for a := 0; a < 5; a++ {
for b := 0; b <= a; b++ {
fmt.Printf("a: %d, b: %d\n", a, b)
}
fmt.Println()
}
The code above defines a loop that has another loop inside it and returns the following result:
a: 0, b: 0
a: 1, b: 0
a: 1, b: 1
a: 2, b: 0
a: 2, b: 1
a: 2, b: 2
a: 3, b: 0
a: 3, b: 1
a: 3, b: 2
a: 3, b: 3
a: 4, b: 0
a: 4, b: 1
a: 4, b: 2
a: 4, b: 3
a: 4, b: 4
And that's it for loops in Go!
Conclusion
As a programmer, it is very important to control the flow of your applications efficiently. In this article, you learned how to use the if
, else if
, else
, and switch
statements to control the execution flow of your applications.
You also explored how to run tasks multiple times in Go using loops. Please leave your feedback, corrections, questions, and suggestions in the comment section, and I'll reply to all of them. Thank you so much for reading, and I'll see you at the next one!