tech

[English] [Japanese]

10.4. Variadic Arguments and Return Values

variable length arguments, return value

By using … for arguments and return values, functions with variable length arguments and variable length return values can be defined.

Here's a sample that makes use of …

// @lnsFront: ok
fn func( ... ) : int, ... {
   let argList = [ ... ];
   let mut total = 0;
   foreach arg in argList {
      when! arg {
         total = total + arg@@int;
      }
   }
   return total, ...;
}

print( func( 1, 2, 3, 4 ) ); // 10 1 2 3 4

The above example defines and executes a function func() that sums the values of the given variadic arguments and returns the sum and the given variadic arguments.

Use … in the function body to indicate the variable length arguments themselves. where … is zero or more stem! values. More on stem! later.

A caller to a function with variable length arguments can specify zero or more arguments of any type.

Generics

Variable length arguments and return values can be declared by using … as above.

However, since all values of … are treated as stem! , the type information is lost.

In the example above, we are passing int data to func(), but the type information is lost, so we need to unwrap or cast to access the value inside func().

To preserve type information, use ...<type> like this:

// @lnsFront: ok
fn func( ...<int> ) : int, ...<int> {
   let argList = [ ... ];
   let mut total = 0;
   foreach arg in argList {
      total = total + arg;
   }
   return total, ...;
}
print( func( 1, 2, 3, 4 ) ); // 10 1 2 3 4

By using ...<int>, it is possible to handle variable length arguments and return values while retaining int type information.

Note that func1() and func2() in the following sample are synonymous.

// @lnsFront: ok
fn func1( ...<stem!> ) {
   print( ... );
}
fn func2( ... ) {
   print( ... );
}
func1( 1, "abc" );
func2( 1, "abc" );