The if-else Construct
This lesson discusses the if-else construct in detail.
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-elseconstruct - The
switch-caseconstruct - The
selectconstruct
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
}
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
}
In a 3rd ...