Sebastian Gomez
Conditionals in Go
Conditionals in Go are a way to control the flow of a program. You can use if, else, else if and switch to decide which instructions run based on certain conditions. Let's look at each structure step by step.
If, Else and Else If
The "if / else if" conditionals are a way to make decisions in programming. They work like this:
- You start with an
ifthat evaluates a condition. If the condition is true, the block of code associated with thatifruns. - If the first
ifcondition is false, control moves to the nextelse if(if there is one). Its condition is evaluated and, if it is true, the block associated with thatelse ifruns. - This process repeats for each
else ifin sequence until a true condition is found or until there are no moreelse ifbranches. When a true condition is found, its block runs and we exit the conditional structure. - If none of the
iforelse ifconditions is true, theelseblock runs (if present), which is the last resort.
Let's look at a first example, a conditional that evaluates whether a variable is greater than the number 10:
package main
import "fmt"
func main() {
var x int = 11
if x > 10 {
fmt.Println("x es mayor a 10")
} else {
fmt.Println("x no es mayor a 10")
}
}Notice the message in the else: since this branch runs whenever the condition x > 10 is false, it also covers the case where x is exactly 10. That is why we say "x is not greater than 10" rather than "x is less than 10", which would leave the value 10 out.
Unlike other languages, in Go conditionals do not require parentheses around the condition being evaluated. On the other hand, the opening brace { is mandatory and must sit on the same line as the condition. If you put it on the next line, the code will not compile.
Now let's look at an if / else if example, where I can add as many cases as I want using the else if syntax:
func ejemploIfElseIf() {
var x int = 11
if x > 10 {
fmt.Println("x es mayor a 10")
} else if x == 10 {
fmt.Println("x es igual a 10")
} else {
fmt.Println("x es menor a 10")
}
}Switch in Go
The switch structure is a flow control mechanism that lets you simplify multiple comparisons of a variable against different values. It works like this:
- Start of switch: the structure begins with the
switchkeyword, followed by the variable or expression you want to compare. - Cases (case): inside the
switchblock you define different cases with thecasekeyword, followed by a specific value you want to compare against theswitchvariable or expression. If the variable or expression matches thecasevalue, the block of code associated with thatcaseruns. - Running a case: when a match is found between the variable and a
case, the code for thatcaseruns and then we exit theswitchstructure. This means only the code of one matchingcaseruns. - Break: although some languages require the
breakkeyword at the end of eachcaseblock to stop control from flowing into the next one, in modern languages like Go thebreakis implicit and you do not need to write it. If you want the opposite behavior, that is, for execution to continue into the nextcase, you can explicitly use thefallthroughkeyword. - default: you can include a
defaultat the end of theswitch, which runs if none of the cases match. It is similar to anelsein anif / elsestructure.
Example of switch:
func ejemploSwitch() {
var x int = 11
switch x {
case 1:
fmt.Println("x es 1")
case 2:
fmt.Println("x es 2")
case 3:
fmt.Println("x es 3")
case 4:
fmt.Println("x es 4")
case 5:
fmt.Println("x es 5")
case 6:
fmt.Println("x es 6")
case 7:
fmt.Println("x es 7")
case 8:
fmt.Println("x es 8")
case 9:
fmt.Println("x es 9")
case 10:
fmt.Println("x es 10")
default:
fmt.Println("x es mayor a 10")
}
}Example of switch / case with ranges:
func ejemploSwitchRango() {
var numeroMes int = 3
var estacion string
switch {
case numeroMes >= 1 && numeroMes < 3:
estacion = "Invierno"
case numeroMes >= 3 && numeroMes < 6:
estacion = "Primavera"
case numeroMes >= 6 && numeroMes < 9:
estacion = "Verano"
case numeroMes >= 9 && numeroMes < 12:
estacion = "Otoño"
default:
estacion = "Ninguna estación del año!"
}
fmt.Println(estacion)
}Example of switch / case with strings:
func ejemploSwitchConTexto() {
var x string = "def"
// Evaluate the value of variable 'x' in a 'switch' structure
switch x {
// If 'x' equals "abc"
case "abc":
// Print the message "x es abc" to the console
fmt.Println("x es abc")
case "def":
// Print the message "x es def" to the console
fmt.Println("x es def")
// If 'x' is neither "abc" nor "def"
default:
// Print the message "x es otra cadena" to the console
fmt.Println("x es otra cadena")
}
}Proposed exercises
Practice with these Go conditional exercises and send your solution as a Pull Request to this repository: Go Para Principiantes.
Note: verify that the "Go Para Principiantes" repository URL is correct and still published before promoting the post. verify
10 conditional exercises in Go:
- Print a different message depending on whether a number is even or odd.
- Given two integers, print the larger of the two.
- Given three integers, print the largest of the three.
- Print a different message depending on whether a number is positive or negative.
- Read an integer and determine whether it is divisible by 5.
- Read an integer and determine whether it is divisible by 3 and 5 at the same time.
- Read two integers and determine whether the first is greater than the second.
- Read three integers and determine whether the first equals the second and the third.
- Read two integers and determine whether the first is less than the second or they are equal.
- Read an integer and determine whether it is even or odd and whether it is positive or negative.
10 switch exercises in Go:
- Print a different message depending on whether a number is between 0 and 5, between 5 and 10, between 10 and 20, or greater than 20.
- Given two integers, print the letter corresponding to the appropriate grade.
- Given three integers, print the letter corresponding to the appropriate grade.
- Read an integer and determine what kind of number it is.
- Read an integer between 0 and 5 and determine which letter it corresponds to.
- Read an integer between 5 and 10 and determine which letter it corresponds to.
- Read an integer between 10 and 20 and determine which letter it corresponds to.
- Read an integer greater than 20 and determine which letter it corresponds to.
- Read an integer and determine whether it is even or odd and whether it is positive or negative.
- Read an integer and determine whether it is divisible by 2, 3, 4, 5 or 6.
3-point summary
- Conditionals in Go (
if,else,else if) let you control the flow of a program based on one or more conditions, with no parentheses around the condition but with the opening brace mandatory on the same line. - The
switchstatement in Go makes it easy to compare a variable against multiple expressions and runs the block associated with the match; thebreakis implicit andfallthroughlets you continue into the nextcasewhen you need it. - Practicing with conditional and
switchexercises in Go helps you improve the flow control of your programs and better understand how to make decisions based on conditions and expressions.
Now that you have learned about conditionals and switch in Go, it is time to put your skills into practice. Work on the exercises above and send your solutions as Pull Requests to the Go Para Principiantes repository.
That's all, I hope this post is useful to you and that you can apply it to a project you have in mind. Leave me a comment if it helped or if you have any questions, and remember that if you liked it you can also share it using the social links below. Good luck and have fun programming in Go.
Sebastian Gomez
Creador de contenido principalmente acerca de tecnología.