this post was submitted on 23 Apr 2026
1 points (100.0% liked)

Golang

2686 readers
7 users here now

This is a community dedicated to the go programming language.

Useful Links:

Rules:

founded 2 years ago
MODERATORS
 

Given the following short function

func example(foo string) error {
    if bar, err := doSomething(foo); err != nil {
        return err
    } else {
        doSomethingElse(bar)
    }
    return nil
}

Why does the linter recommend I change the if block to

    var bar whateverType
    if bar, err = doSomething(foo); err != nil {
        return err
    }
    doSomethingElse(bar)
    return nil
}

In my mind the former example restricts the bar variable to the smallest scope that is needed, and more clearly identifies doSomethingElse as something that should only happen if err != nil.

I know it's redundant, but now if I want to change it to an else if ... chain I don't have to worry about accidentally including or excluding code from that block, I already know exactly what's supposed to be in it. I just feel like it's a safer programming practice.

But looking forward to other opinions and discussion. Thanks!

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here