11

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 Answers 4

12

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

I like the consistency and clarity of that convention.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

4

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.

Comments

3

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

1 Comment

Well, you need it if you want to return from within control flow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.