Conditional statements are constructs that allow a program to perform different operations depending on the value of a Boolean expression. In simple terms, these statements control the flow of our program and determine what to do next based on whether a specific condition is met or not. In this topic, we'll learn about the conditional statements we can implement in Go.
The if statement
When we develop our code, we often need to make decisions based on some condition. In Go, we can do this with the help of the if statement. The if statement is used to execute a block of code only if the specified condition is true; otherwise, the program skips this part of the code.
The simplest form of the conditional statement consists of the keyword if, followed by a boolean expression and a body enclosed in curly braces. Let's take a look at the code example below:
package main
import "fmt"
func main() {
number := 4
if number % 2 == 0 { // checks if the number is even
fmt.Println("The number", number, "is even")
}
}In the seventh line, the condition number % 2 == 0 evaluates whether the remainder of dividing number by 2 is 0 or not. Since the remainder is 0, the condition is true and the program prints "The number 4 is even" to the terminal.
Alternatively, if the value of number was 3 instead of 4, the condition would become false, the program would skip the body within the if statement and finish with an empty output.
The if-else statement
It is essential to know that you can extend an if statement with an else statement and execute another block of code if the condition is false. Let's take a look at an updated version of the code snippet above:
package main
import "fmt"
func main() {
number := 5
if number % 2 == 0 { // checks if the number is even
fmt.Println("The number", number, "is even")
} else {
fmt.Println("The number", number, "is odd")
}
}In the sixth line, we can see that the updated value of number is the odd number 5, and in the ninth line, we can see the newly implemented else statement. In this case, our program will evaluate the number % 2 == 0 condition as false, skip the body of the if statement and execute the body of the else statement instead, printing "The number 5 is odd" to our terminal.
The if-else if statement
In contrast to the if-else statement that checks if the condition is either true or false, the else if statement can help us check several possible conditions. Let's evaluate the else if statement in action in the code snippet below:
package main
import "fmt"
func main() {
var score int = ... // Your test score goes here.
if score > 90 {
fmt.Println("Your grade is A. Congratulations!")
} else if score > 80 {
fmt.Println("Your grade is B. Good enough.")
} else if score > 70 {
fmt.Println("Your grade is C. Could've done better!")
} else if score > 60 {
fmt.Println("Your grade is D. Study more next time!")
} else {
fmt.Println("Your grade is F. Terrible! you failed the test!")
}
}In every if-else chain, the conditions are evaluated from top to bottom. For example, if the value of the score variable is 92, the program will execute the first condition: score > 90 and print "Your grade is A. Congratulations!". However, if the value of score is 64 instead, the program will skip the bodies of all other conditions until it reaches the fourth condition: score > 60. Since this condition is true, the program will execute the body within the fourth condition, printing "Your grade is D. Study more next time!" to our terminal.
The switch statement
So far, we've seen the if, else and else if statements. They work great for simple evaluation cases, but the code becomes difficult to read when we use them with many conditions. For situations like this, the switch statement provides a simple and organized way to choose between multiple conditions. Let's check out the switch statement in action when it's used in a computer game programmed in Go:
package main
import "fmt"
func main() {
var selection string = ... // Your selection goes here.
switch selection {
case "new":
fmt.Println("Starting a new game!")
...
case "load":
fmt.Println("Loading a saved game.")
...
case "exit":
fmt.Println("Exit the game.")
...
default:
fmt.Println("Invalid selection. Try again.")
}
}In the sixth line, we have the variable selection that we will evaluate in the switch construct through several case statements. For example, if the value of selection was "load", the program would execute case "load" and print "Loading a saved game." to the terminal, allowing us to load and continue a previously saved game.
Near the end of the switch statement, we can see the special default case. It gets executed if none of the other cases is true. You can place thedefault case in any part of the switch statement, but following the Go coding style convention, you should place it at the end of the switch statement.
Finally, if you are familiar with other programming languages, such as Java or the C family of languages, you may have seen the break statement used at the end of each case body. In Go, the break statement is provided automatically, so there is no need for us to hardcode it within our switch statement. In simple terms, the function of the break statement is to step out of the switch construct after executing the code block within the case.
The versatility of the switch statement
In Go, we have versatile switch statements. This means we can match a variable to a single value, multiple values, match it based on expressions and logic, or even use it without an expression, which would be the equivalent of a multi-line if-else statement. Let's take a look at using the switch statement without an expression:
package main
import "fmt"
func main() {
var number int = ... // Your number goes here.
switch { // Equivalent to `switch true`
case number % 2 == 0:
fmt.Println("The number", number, "is even")
case number % 2 != 0:
fmt.Println("The number", number, "is odd")
}
}This switch statement will evaluate each case as a boolean expression; since this example is very similar to the previously explained code snippets, you can easily infer the program's output based on the value of the number variable.
An important detail is that all case statements within the switch construct must be unique. Every constant, even in a list of multiple values, is checked against the entire switch statement, and if there is a duplicate value, an error will be reported when trying to compile our program. Let's take a look at an invalid switch statement:
package main
import "fmt"
func main() {
letter: = "a"
switch letter {
case "a", "e", "i", "o", "u":
fmt.Println("The letter", letter, "is a vowel")
case "a", "e", "i", "o", "u":
fmt.Println("The letter", letter, "is a vowel")
default:
fmt.Println("The letter", letter, "is a consonant")
}
}Since the second case is a duplicate of the first case, our program will output the following error when we try to compile it:
.\main.go:11:7: duplicate case "a" in switch
previous case at .\main.go:9:7
.\main.go:11:12: duplicate case "e" in switch
previous case at .\main.go:9:12
...Conclusion
Let's sum up what we've learned so far:
The
ifconstruct is the simplest form of conditional statement in Go. It only executes the code block within theifbody if the evaluated expression istrue.The
elsestatement can extend theifstatement by evaluating if the expression is false instead of true.The
else ifstatement extends theifconstruct by letting us evaluate several different conditions.The
switchstatement provides a simple and organized way to choose between multiple conditions. We can use it to match a variable to a single value, multiple values, match it based on expressions and logic, or even use it without an expression.The
casestatements within theswitchconstruct must always be unique! Otherwise, our program will report a duplicate error when trying to compile the repeating part.
We're not done yet! Let's do some exercises now and test our knowledge of conditional statements.