Conditional Statements and Loops
Learn how to make decisions and repetitions in Go.
We'll cover the following...
Conditional statements
Conditional statements perform various actions based on specific conditions. The developer specifies one or more conditions that the program executes. Particular statements are returned based on the outcome. Go uses logical and comparison operators to create conditions for different decisions. We’re going to explore the following:
- The
ifstatement - The
if elsestatement - The
else ifstatement - The nested
ifstatement - The
switchstatement
The if statement
The if statement executes a code block only if the specified condition is true.
package mainimport ("fmt")func main() {bicycles:= 9tricycles:= 3Username := "Greghu"if bicycles > tricycles {fmt.Println("We have more bicycles than tricycles")}if Username == "Lizzy" {fmt.Println("Elizabeth's username is Lizzy")}// This condition will not print out a result, because it is not true.}
The if else statement
The if else statement allows us to run one block of code if the specified condition is true and another block of code if it’s false.
package mainimport ("fmt")func main() {Username := "Greghu"if Username == "Lizzy" {fmt.Println("Elizabeth's username is Lizzy")} else {fmt.Println("Greg's username is", Username)}// Remember starting our else statement on a different line would raise an error.}
The else if statement
The else if statement allows us to combine multiple if else statements.
package mainimport ("fmt")func main() {Username := "Greghu"if Username == "Lizzy" {fmt.Println("Elizabeth's username is Lizzy")} else if Username == "Greghu" {fmt.Println("Greg's username is", Username)} else {fmt.Println("Ooops, please sign up!")}}
The nested if
The nested if statement is an if statement within another if statement.
package mainimport ("fmt")func main() {number := 7if number <= 9 {fmt.Println(number, "is less than 9.")if number < 11 {fmt.Println(number, "is also less than 11.")}} else {fmt.Println(number, "is greater than 9 and 11.")}}
Here’s what’s happening in the code above:
The first
if...