Multiple Return Values in Erlang

Erlang has built-in support for multiple return values through tuples. This feature is used often in idiomatic Erlang, for example to return both result and error values from a function.

-module(multiple_return_values).
-export([main/0]).

% The {integer(), integer()} in this function spec shows that
% the function returns a tuple with 2 integers.
-spec vals() -> {integer(), integer()}.
vals() ->
    {3, 7}.

main() ->
    % Here we use pattern matching to extract the 2 different 
    % return values from the function call.
    {A, B} = vals(),
    io:format("~p~n", [A]),
    io:format("~p~n", [B]),

    % If you only want a subset of the returned values,
    % use the underscore '_' as a placeholder.
    {_, C} = vals(),
    io:format("~p~n", [C]).

To run the program:

$ erlc multiple_return_values.erl
$ erl -noshell -s multiple_return_values main -s init stop
3
7
7

In Erlang, multiple return values are typically handled using tuples. The function vals/0 returns a tuple {3, 7}, which is then pattern matched in the main/0 function to extract individual values.

The concept of “blank identifier” in Go is similar to the underscore _ in Erlang, which is used to ignore specific values in pattern matching.

Accepting a variable number of arguments is also possible in Erlang functions; we’ll look at this in a future example.