Start learning free

LESSON 68 OF 338 · CONDITIONAL STATEMENTS

If Else in Go: Choosing Between Two Branches

Lesson Read the full explanation

An else block runs when the if condition is false.

passed := false

if passed {
    fmt.Println("Passed the test")
} else {
    fmt.Println("Failed the test")
}

Only one branch runs: the if body when passed is true, otherwise the else body.

Assignment
Complete the else branch so the failed message is printed when passed is false.


STEP 1 OF 1
    Ctrl + Enter to check

    GO · CONDITIONAL STATEMENTS

    If Else in Go, explained

    What if-else does

    An if on its own runs code or skips it. Adding else turns that into a choice between two blocks: the if body runs when the condition is true, and the else body runs otherwise. Exactly one of them runs.

    passed := false
    
    if passed {
        fmt.Println("Passed the test")
    } else {
        fmt.Println("Failed the test")
    }
    

    Since passed is false, this prints Failed the test.

    The syntax rules

    • else has no condition. It runs whenever the if condition is false, whatever the reason.
    • else goes on the line of the closing brace. Write } else {. Go adds a semicolon automatically after a line that ends with }, so an else on a new line is a syntax error: unexpected else, expected }.
    • Both blocks need braces, even when each holds a single statement.

    Negating a condition

    The ! operator flips a boolean. If you want to run code when something is false, you can test the negation instead of using an empty if:

    if !passed {
        fmt.Println("not passed")
    }
    

    This prints not passed when passed is false. An else is clearer when both outcomes need a response.

    Chaining with else if

    When there are more than two outcomes, put another if after else. The conditions are tested from top to bottom and the first true one wins; the rest are skipped:

    score := 6
    
    if score >= 9 {
        fmt.Println("A")
    } else if score >= 5 {
        fmt.Println("B")
    } else {
        fmt.Println("C")
    }
    

    This prints B. The first condition fails, the second holds, so the final else never runs. Order matters: if the score >= 5 test came first, a score of 9 would also print B.

    Nesting

    A branch can contain another if. This is legal, but each level of nesting makes the code harder to follow:

    hasAccount := true
    paid := false
    
    if hasAccount {
        if paid {
            fmt.Println("full access")
        } else {
            fmt.Println("free access")
        }
    } else {
        fmt.Println("please sign up")
    }
    

    This prints free access. Every else pairs with the if whose block it follows, and the mandatory braces make that pairing explicit, so Go has no "dangling else" ambiguity. When nesting grows past two levels, an else if chain or a combined condition is usually easier to read.

    Conditions are expressions

    Anything that produces a bool can be a condition: a variable, a comparison such as grade < 5, a call to a function that returns bool, or several of these combined. You can also store the result first and test it later: passed := grade >= 5 followed by if passed {. Naming the result often reads better than a long condition inside the if line, because the name says what the test means. The exercise below uses a variable that already holds the boolean.

    Zero values

    A bool variable declared without a value starts as false. Go sets every variable to its type's zero value, so var passed bool followed by if passed takes the else branch. The lesson spells the value out with var passed bool = false, which means the same thing.

    The exercise

    The starter code has an if that prints "Passed the test" but no else. With passed set to false, it prints nothing at all. The task is to make the program report a result in both cases.

    1. After the closing } of the if block, on the same line, add else {.
    2. Inside, print "Failed the test" with fmt.Println.
    3. Close the new block with }.

    The result:

    var passed bool = false
    if passed {
        fmt.Println("Passed the test")
    } else {
        fmt.Println("Failed the test")
    }
    

    Note that the two messages are different strings. The lesson's tests look for Failed the test exactly, so keep the wording and capitalisation as given.

    Common mistakes

    • else on a new line, which fails to compile.
    • Giving else a condition. else (passed == false) is invalid; use else if when a second test is really needed.
    • Checking the same thing twice. Code like if passed {...} followed by a separate if !passed {...} works but repeats the test. A single if/else states it once.
    • Misordering an else if chain, so a broad condition hides the narrower ones below it.

    Key takeaways

    • if/else runs exactly one of two blocks.
    • Write } else { on one line.
    • else takes no condition; else if adds one.
    • Conditions in an else if chain are checked in order, and the first true one wins.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free