Hacker News new | ask | show | jobs
by usrbinbash 1598 days ago
Easily fixed using lexical scopes:

    func doThing() string {
        result := "OK"

        {
            var err error
            if result, err = somethingElse(); err != nil {
                return "ERROR"
            }
        }

        return result
    }
`err` is introduced in the lexical scope, `result` isn't so it still refers to the string from the surrounding scope. `err` does not pollute the surrounding scope.

You can also try the complete version here: https://go.dev/play/p/kDEB11YdvSs

1 comments

In my experience this isn’t idiomatic Go and would definitely turn heads in a code review. But in such a small function, it’s fine to just not worry about the lifetime of your variables (and in bigger functions you can often decompose into smaller functions).
I agree. The idiomatic thing here would be to simply declare `var err error` in the surrounding scope, especially since this example is a small function where this wouldn't matter.

But "idiomatic" always takes a backseat compared to technical necessity. If there is a requirement, for some reason, to limit the scope of `err` and still allow `result` to be changed in the if's pre-assignment, then this is the way to do it.