Skip to main content

Variadic Parameters

Variadic parameters allow passing variable (zero or more) number of arguments to a function. Variadic parameters must always appear at the end of the parameter list. There can be no more than one of them in the same parameter list.

The following example uses the write unix syscall to print all the arguments passed to the variadic_print function -

extern "C" fn write(fd: c_int, buf: *char, count: c_size_t): c_ssize_t;

fn variadic_print(... args: str) {
comptime for arg in args {
write(1, arg.ptr(), arg.size());
}
}

fn main() {
variadic_print("Hello ", "World! ", "Good ", "Night");
}

As shown above, a comptime for loop is used to expand the variadic arguments. Note that in the above example, an explicit type str was specified for the variadic parameter args, making the compiler type check every variadic argument against it. This however, isn't required, you can leave the type unspecified, allowing you to pass arguments of any type to the function.

Swirl monomorphizes variadic functions, i.e., a new function is generated by the compiler behind the scenes for every unique call to a variadic function.

Stay informed