suppose that there is a function with several return values
function foo()
...
ret1, ret2, ret3
end
and suppose that a caller is interested in a particular subset of the return values and not all of them.
How could this be implemented in an expressive manner?
My thoughts:
If only the first output is desired, then it is straightforward
ret1 = foo() # ret2 and ret3 are not going to be accessible in the caller scope
if only one output is desired,
I could imagine returning the outputs as a named tuple, e.g.
function foo()
...
(x = ret1, y = ret2, z = ret3)
end
y = getindex(foo(),:y) # the caller does not need to store references to x and z in dummy variables
# and implies that only y is going to be used
I am wondering if there is still a better way to express this and how to handle case 3, i.e. if only accessing more than one output is desired.
I personally like NamedTuples for multiple returned values because if I’m refactoring later and need to add additional returned values, I don’t have to worry about how the order might affect every single call site. And should I later decide that the set of returned values is coherent enough to be a struct, I’ve already started accessing fields with properties so it’s easier to find and replace them.
But really, does something “come with any syntactical advantages” is really up to your experience of what is more readable and useful!