Charting Our Coding Trajectory: Overview of Conditional Statements in Go

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!

Mapping the If and If-Else Constellation

The structure of if and if-else control flow in Go reflects the following:

if condition {
    // action if condition is true
}

// additionally

if condition {
    // action if condition is true
} else {
    // action if condition is false
}

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.

Probing the Nebula of Go's If-Else Statement

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:

var oxygenLevel = 78  // The level of oxygen on the planet

if oxygenLevel > 20 {
    fmt.Println("Planet has breathable air!") // Oxygen level is suitable
} else {
    fmt.Println("Oxygen level too low!") // Oxygen level is not high enough
}
// The code prints: Planet has 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!".

Multiple Conditions: The Else If Statement

When dealing with multiple conditions, we fall back on else if:

var oxygenLevel = 58
if oxygenLevel > 70 {
    fmt.Println("Excellent Oxygen level!")
} else if oxygenLevel > 50 {
    fmt.Println("Oxygen level is acceptable.")
} else {
    fmt.Println("Oxygen level is too low!")
}
// The code prints: Oxygen level is acceptable.

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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal