Using Conditionals
Explore how to implement conditional logic in Go using if, else, else if, and switch statements. Understand Go’s unique features such as init statements within conditionals and brace style rules to write clear, idiomatic code that handles multiple conditions effectively.
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:
Here's a simple example:
The statements within {} in if will execute if x has a value greater than 2.
Unlike most languages, Go has the ability to ...