Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Just a wild guess, not sure about the true reasons: it adds the information that the control flow can hit the end of the function and that it actually returns something. All that given the writer doesn't write syntactically superfluous returns.

Also I slightly disagree with you that named return values are for short code. This may be true in functions that return at many points. For other functions it may need some otherwisely added boilerplate. If you write inside an if-block f, err := os.Open(...) that err is a different one than your return value err. So you would need to add var f *os.Open above the if to write f, err = os.Open(...).

Having that said, IMHO the greatest pro of named return values is well understandable code, in particular for libraries.



1. I'm not sure I understand. If a function shouldn't hit the end, put a panic there. If you want to emphasize that it does, put an explicit "return;" in. But requiring you to put in a "return;" yields no information at all. Dead code isn't an error.

2. You're right, they're not only for short code. That however is where the forced "return" is most glaring.


I can see the benefit of the forced return, but only because it's bitten me in the past.

In Python, if you don't say `return` the function returns `None`.


That's less of an issue for Go as aside interface{}, fundamental types can't be nil. Plus the instance we're talking about here is with named returns, so the variables are already initialised.

From a personal perspective, I find having to include "return" a pain as there's times when it's completely unnecessary. eg in switch statements or if else where each condition has it's own return. While it's an easy fix for if else (just drop the else / default case), it makes the code look a little less pretty in my opinion.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: