Search⌘ K
AI Features

The if-else Construct

Explore how the if-else construct allows you to make conditional decisions in Go programs. Understand how to write clear, readable conditions, use else if branches effectively, and implement initialization statements within if conditions to control execution flow precisely.

We'll cover the following...

Introduction

Until now, we have seen that a Go program starts executing in main() and sequentially executes the statements in that function. However, we often want to execute certain statements only if a condition is met, which means we want to make decisions in our code. For this, Go provides the following conditional or branching structures:

  • The if-else construct
  • The switch-case construct
  • The select construct

Repeating one or more statements (a task) can be done with the iterative or looping structure:

  • for (range) construct

Some other keywords like break and continue can also alter the behavior of the loop. There is also a return keyword to leave a body of statements and a goto keyword to jump the execution to a label in the code. Go entirely omits the parentheses ( and ) around conditions in if, switch and for-loops, creating less visual clutter than in Java, C++ or C#.

The if-else Construct

The if tests a conditional statement. That statement can be logical or boolean. If the statement evaluates to true, the body of statements between { } after the if is executed, and if it is false, these statements are ignored and the statement following the if after } is executed.

if condition {
    // do something
}
if structrure
if structrure

In a 2nd variant, an else, with a body of statements surrounded by { }, is appended, which is executed when the condition is false. It means we have two exclusive branches, and only one of them is executed:

if condition {
// do something
} else {
// do something else
}
if  and else structrure
if and else structrure

In a 3rd ...

one else-if along with if and else structrure
one else-if along with if and else structrure