Julia Language Multiple return values


Example

Tuples are frequently used for multiple return values. Much of the standard library, including two of the functions of the iterable interface (next and done), returns tuples containing two related but distinct values.

The parentheses around tuples can be omitted in certain situations, making multiple return values easier to implement. For instance, we can create a function to return both positive and negative square roots of a real number:

julia> pmsqrt(x::Real) = sqrt(x), -sqrt(x)
pmsqrt (generic function with 1 method)

julia> pmsqrt(4)
(2.0,-2.0)

Destructuring assignment can be used to unpack the multiple return values. To store the square roots in variables a and b, it suffices to write:

julia> a, b = pmsqrt(9.0)
(3.0,-3.0)

julia> a
3.0

julia> b
-3.0

Another example of this is the divrem and fldmod functions, which do an integer (truncating or floored, respectively) division and remainder operation at the same time:

julia> q, r = divrem(10, 3)
(3,1)

julia> q
3

julia> r
1