Julia Return Values
A return value is the result a function sends back to the code that called it. The caller can print that result, store it, or use it in more work.
Return sends a value back to store
The word return hands the result to the caller. The caller stores it and can keep using it.
function double(x)
return x * 2
end
result = double(6)
println(result)
println(result + 1)The last expression is returned too
This function has no return word. Its last line is the only line, so that value is sent back.
function square(x)
x * x
end
println(square(4))
println(square(5))One return can send back several values
Writing two values after return sends them back as a tuple. The printed pair keeps its parentheses and order.
function swap(a, b)
return b, a
end
println(swap(3, 8))Example
function double(x)
return x * 2
end
function nextvalue(x)
x + 1
end
function both(x)
return double(x), nextvalue(x)
end
println(both(5))
println(double(3) + nextvalue(3))Key points
- Return value: the result a function sends back to its caller.
- Return: the word return sends a value back and ends the function at once.
- Last expression: without return, the value of the last line is sent back.
- Tuple: a fixed group of values written in parentheses, such as (3, 4).
- Several values: writing return a, b sends both values back as one tuple.
- Stored result: an assignment can save a returned value in a variable.
In this example, double uses return and nextvalue returns its last expression. The function both calls the other two and returns both results as a tuple. Last, the two returned values are added together and print as 10.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
A function body ends with the line x + 3 and has no return word. What does the function send back for an argument of 2?