4 ms·
I think you can also do the second in Go with named returns, e.g. func sum(nums []int) (result int) { for _, n := range nums { result +
by onei 4y ago
I think you can also do the second in Go with named returns, e.g.
func sum(nums []int) (result int) {
for _, n := range nums {
result += n
}
}
No clue if it's an idiomatic usage, and named returns always felt a little too magic for me.
- zimpenfish 4y agoIt's kinda fine if it's a short function like that[1]. When you get above 10-15 lines in a function though, it's easy to lose track of what's a return variable and what isn't. [1] and everything in the codebase uses that style otherwise it's annoying to have to context-switch every 5 minutes.
- mikepurvis 4y agoLots of languages will implicitly return the final expression— I feel like that's a decent compromise. Not quite as magical as an actual named variable that just exists, but not as clunky as needing as explicit `return` every time.
- tsimionescu 4y agoHonestly, I don't like that style for languages which allow multiple side-effects as well. For example, (progn (print "something") 0) Is honestly pretty ugly from my point of view.
- mikepurvis 4y agoSure, definitely, and in a case like that (say, in rust), I would just put an explicit `return` in. But there are lots of other scenarios where the result is naturally being returned by the final expression and it's quite convenient to elide the extra keyword.
- Falkon1313 4y agoI always disliked implicit returns, and over the years and having dealt with many more codebases, some quite large, I've learned to dislike any implicitness. I would much prefer that you must explicitly return a value (even if it's through an implicitly declared 'Result' variable) rather than just 'try to guess what happened here, in this long function with lots of expressions'. There are a few exceptions, like Forth, where you really have to keep the current state of the stack in mind at all times anyway. Those exceptions naturally tend toward very small functions. Most languages don't, and the result is inevitably difficult to understand bugs.
- ilyt 4y agoyou can do func sum(nums []int) (result int) { for _, n := range nums { result += n } return } and it will work same as if you would do return result As for omitting return entirely I hated it in every language where I saw it. It just feels wrong to not have return in functions that return stuff
- jdmichal 4y agoI think missing `return` works if the language is designed around everything being expressions, so the function is just written as a single expression. I agree that in procedural type paradigms I like having the `return` keyword over things like "return the result of the last expression".
- int_19h 4y agoThis case is a bit different - omitting the return simply returns the implicitly declared result variable, which makes perfect sense.