Optional output arguments

A nice thing about MATLAB is that the caller can request multiple function outputs, i.e. you can either do:

y = foo(5);

[y, info] = foo(5);

This is quite practical because you can then easily do baz(bar(foo)) if info is not too important. I guess that this cannot be done in such a straightforward way in Julia. Is this correct?

You can also do

y, _ = foo(5)

if you don’t want the second element.

and it works with slurp as well

y, _... = foo(5)

also, in slightly more cursed way, it also works if the assignment expression looks like a tuple unpacking even of a shorter length

(y,) = foo(5)

It’s correct that Julia doesn’t provide any way for a function to introspect how many output values the caller will keep.

In case the extra outputs are free or cheap to compute, just return them and let the caller discard them, as proposed by other comments.

If the extra output is expensive and something you don’t want to spend time on unless it’s wanted, my preferred way is to add an extra input with a mutable struct, vector, or Ref that the function can fill in with the desired information. E.g.

function foo(x, info = nothing)
    y = ...
    if !isnothing(info)
        # Fill in `info`.
    end
    return y
end