Greetings, Go astronaut in training! Today's itinerary includes studying the mainstay of programming control flow: conditional statements. These mechanisms steer the course of our Go program. Are you strapped in and ready to explore the if-else statement? Let's start the countdown now!
The structure of if and if-else control flow in Go reflects the following:
Here, when the given condition becomes true, we take action via the if block. When the condition is false, we have an optional else block to resort to.
By using the if statement in Go, we command the machine to undertake specific actions only when conditions are met. Let's imagine deciding to land on a planet with breathable air:
In the example, the statement if oxygenLevel > 20 tests if the oxygen level is greater than 20. If the test passes (true), it prints: "Planet has breathable air!". If it fails (false), the else clause provides an alternative command and prints: "Oxygen level too low!".
When dealing with multiple conditions, we fall back on else if:
With the else if keyword, we can map out alternative routes until we find a fitting one, which allows us to adapt suitably to different levels of oxygen. As soon as one condition is met, the program disregards subsequent else if conditions.
