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

Golang

2737 readers
1 users here now

This is a community dedicated to the go programming language.

Useful Links:

Rules:

founded 3 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!

you are viewing a single comment's thread
view the rest of the comments
[–] who@feddit.org 1 points 4 months ago* (last edited 4 months ago)

I can't speak for Go's maintainers, but your story fits a pattern I've noticed: The language, standard library, and toolchain are excessively prescriptive about how things should be done, while insufficiently considerate of diversity in people's needs. Ergonomics suffer because of it, as do other things that I find important.

Nit: I think you meant to write, "should only happen if err == nil."

@RemindMe@programming.dev 36 hours