← Back to context

Comment by nirui

15 hours ago

The chosen example:

    bar, err := foo()
    if err != nil {
        return err
    }
    if err = foo2(); err != nil {
        return err
    }

Sounded more like a nitpicking.

If you really care about scope while being able to use `bar` later down, the code should be written as:

    bar, err := foo()
    if err != nil {
        return err
    }
    err = foo2() // Just reuse `err` plainly
    if err != nil {
        return err
    }

which actually overwrites `err`, opposite to "shadowing" it.

The confusing here, is that the difference between `if err != nil` and `if err = call(); err != nil` is not just style, the later one also introduces a scope that captures whatever variables got created before `;`.

If you really REALLY want to use the same `if` style, try:

    if bar, err := foo(); err != nil {
        return err
    } else if bar2, err := foo2(); err != nil {
        return err
    } else {
        [Use `bar` and `bar2` here]
        return ...
    }