Hacker News new | ask | show | jobs
by menthe 895 days ago
I hope you realize that this won’t even compile.

The err in your if is a newly allocated variable by :=, different than the err allocated by the x prototype, and you’d also return a nil error even if impl returned an error.

The Go compiler is smart enough to prevent you from doing this beginner mistake:

result parameter err not in scope at return. inner declaration of var err error.

https://go.dev/play/p/VdWVOL51wZf

You would have to first declare thing prior to the if statement, then replace := by = .. the beauty of adding verbosity and longer-lived variables for the sake of trying to write return instead of return err in Go.

1 comments

I wrote it that way because that was I was looking at in the example code. You're mostly right. The example from my own code, of course, looks more like this:

https://go.dev/play/p/qdjnH3JhzTN

Which does work because the rules on := are loose, but the if captured version creates a new scope that can't be shared with the return variable.