golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.92k stars 17.65k forks source link

proposal: Go 2: remove bare return #21291

Closed earthboundkid closed 1 year ago

earthboundkid commented 7 years ago

(I couldn't find an existing issue for this, so please close if this is a duplicate and I missed it.)

I propose getting rid of bare returns. Named return values are great, keep those. Bare returns are more trouble than they are worth, eliminate them.

millerlogic commented 4 years ago

@mvdan Good point, I think there is a middle ground which doesn't involve demonizing them. I think I read an idea similar to: not explicitly returning a value if you previously assigned to the return variable. It might even be implemented somewhere, but I never hit it. So that would mean my hello example would error without a naked return, and your example would succeed because foo or bar weren't assigned to.

dustinevan commented 4 years ago

I think these should be removed from the tour of go, that way newer go developers aren't encouraged to use these. In practice they're just a cognitive tax. The few I've seen always required my brain to say "wait what?!...oh yeah, naked returns and named return values" I understand maybe leaving them in the tour so everyone knows, but there's an entire page dedicated to them.

kokizzu commented 2 years ago

so.. variable shadowing is the problem, but named return values + naked return got to blame..

DeedleFake commented 2 years ago

This is actually the one situation where shadowing is rarely a problem. The variables aren't shadowed in the top-level scope of the function, and if they're shadowed and there's a naked return in a sub-scope, it's a compile-time error. The main issue is if the variable is referenced from somewhere else, such as a closure, and then is accidentally shadowed somewhere, but that problem is not at all unique to named returns.

Diegovsky commented 2 years ago

why not just add a special return syntax for naked returns? That way there is no cognitive overhead of checking named returns since the special return syntax already implies that.

Something like return ! naked return

Bikeshedding ensues. The goal here is to differentiate naked returns from void returns.

Also this can be opt-in to keep working code working and eventually turned into a lint or error.

ianlancetaylor commented 1 year ago

Removing an existing language feature requires a clear consensus that it is harmful in some way. For example, the feature might be widely misunderstood, and might lead to many bugs in existing code. I don't see that here. I understand that people don't like bare returns--I'm not especially fond of them myself--but I don't see people reporting bugs due to bare returns. So this is not a change that we are going to make, and I'm going to close this issue. Thanks.