return keyword [language.return]
Use return for returning early from a function, for example to reduce nesting.
In other cases, prefer implicit return expressions.
func f(v: ref Xxx): int =
if v == nil:
# early return to reduce nesting of happy case
return 0
...
# Prefer implicit return expressions in most other cases
if conditions:
v[].value
else:
0
func short(): int =
42 # simple expressions also qualify
Pros
- Can simplify complex conditions and nesting
- Explicitly shows where return control flow hapens
Cons
- Brittle due to lack of compile-time enforcement of exhaustiveness of control flow and initialization
- When nested deeply, can make conditions for early return difficult to understand
- Surprising semantics in templates and macros
Practical notes
- beware of
returnintemplates since thereturnhappens after template expansion!- ...especially when changing a
procto atemplate
- ...especially when changing a
returndeep inside a complex set of conditionals indicates that the function likely needs refactoringreturnof avarrisks returning instances that have not been fully initialized- this in particular applies to the implicit
resultvariable.
- this in particular applies to the implicit
return expris shorthand forresult = expr; return result- this reduces toreturn resultwhen there is no expression