9
votes

when should a function in Julia have a return statement using the return keyword and when should it just return by having the variable I want to return at the end of the function?

I was reading the Julia docs and it seems like there's quite a bit of literature on the subject found here.

My understanding is that the convention is to always use return if you are trying to break out of the function and to otherwise just have the variable you want to return at the end of the function.

Is my understanding correct or am I missing something here?

4

4 Answers

11
votes

The Blue Style guide recommends always using return in long-form functions definitions.

I like the consistency and clarity of that convention.

4
votes

It is a matter of taste, but I strongly prefer explicit return statements in multi-line functions.

I always do a double take and get confused for a second-and-a-half whenever I see a lone variable or expression dangling on its own on the last line. I find it weird and inelegant.

Explicit return statements improve readability a lot, imho.

4
votes

Technically speaking, you do have to use the return keyword if returning CodeInfo from a @generated function. Due to a long standing bug https://github.com/JuliaLang/julia/issues/25678 Which comes up if you are trying to implement Cassette style complier passed or similar (see a blog post I wrote on that)

With that said, this is so incredibly obscure that I really hesitate to make this answer. For all but dozen or so people who will ever try and do that kinda thing, The presence of return or not in the last statement is purely a mater of style.

3
votes

This is purely stylistic. It's never necessary to use the return keyword. Personally, I don't use it.