Using Conditionals
Understand conditionals in Go, including if/else and switch blocks.
We'll cover the following...
We'll cover the following...
Go supports the following two types of conditionals:
The
if/elseblocksThe
switchblocks
The standard if statement is similar to other languages with the addition of an optional init statement borrowed from the standard C-style for loop syntax.
The switch statements provide a sometimes-cleaner alternative to if. So, let's jump into the if conditional.
The if statements
The if statements start with a familiar format that is recognizable in most languages:
if [expression that evaluates to boolean] {...}
Here's a simple example:
Go (1.18.2)
x:=4if x > 2 {fmt.Println("x is greater than 2")}
The statements within {} in if will execute if x has a value greater than 2.
Unlike most languages, Go has the ability to execute a ...