Search⌘ K
AI Features

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/else blocks

  • The switch blocks

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:

Go (1.18.2)
if [expression that evaluates to boolean] {
...
}

Here's a simple example:

Go (1.18.2)
x:=4
if 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 ...