Multiple Return Values in D Programming Language

D supports multiple return values, which is a useful feature for returning both result and error values from a function.

import std.stdio;

// The (int, int) in this function signature shows that
// the function returns 2 ints.
auto vals()
{
    return tuple(3, 7);
}

void main()
{
    // Here we use the 2 different return values from the
    // call with multiple assignment.
    auto result = vals();
    int a = result[0];
    int b = result[1];
    writeln(a);
    writeln(b);

    // If you only want a subset of the returned values,
    // use the placeholder _.
    auto [_, c] = vals();
    writeln(c);
}

To run the program:

$ dmd multiple_return_values.d
$ ./multiple_return_values
3
7
7

In D, we use the tuple type from the std.typecons module to return multiple values. The auto keyword is used for type inference. When calling the function, we can use tuple unpacking to directly assign the returned values to variables.

D also supports the concept of placeholder variables using _, similar to the blank identifier in other languages. This allows us to ignore specific returned values if we’re only interested in a subset of them.

Next, we’ll look at how D handles functions with a variable number of arguments.