Variadic Functions (v0.2.2)
Functions that accept a variable number of arguments.
Overview
A function marked with @arbitraryArgs accepts any number of extra arguments. The extra arguments are collected into a variable argument list that the body reads with the arbitraryArgs builtins.
The named parameters are declared as usual; the extra arguments are implicit. Callers can pass any number of them.
Primary source: syntax/variadic/variadic.md
Syntax Signatures
fn printValues(fmt: CString) s32 @public @arbitraryArgs {
// ...
}
fn readTwo(first: s32) s32 @public @arbitraryArgs {
var list: ptr = arbitraryArgs();
var a: s32 = arbitraryArgFrom(list, s32);
var b: s32 = arbitraryArgFrom(list, s32);
return a + b;
}
Behavior and Use
For variadic functions defined in Thrust without @extern, the compiler prepends a hidden usize argument with the number of extra arguments. Use arbitraryArgsCount to read it.
FFI variadic functions (@extern) keep the C ABI and do not carry the hidden count.
Reading Arguments
The list is read with the arbitraryArgs builtins.
- arbitraryArgs() returns the current variable argument list as ptr.
- arbitraryArgFrom(list, T) reads the next argument of type T from list.
- arbitraryArgsCopy(list) copies list so it can be read independently.
- arbitraryArgsEnd(list) ends a list created with arbitraryArgsCopy or arbitraryArgsStart.
- arbitraryArgsCount() returns the hidden argument count of the current variadic function.
- arbitraryArgsStart() starts a new list for later use.
Supported Types
arbitraryArgFrom only accepts scalar and pointer types.
- Allowed types: integers, floats, pointers, bool, and char.
- Reading a struct or array type is rejected; pass a pointer instead.
Example
fn countArgs(first: s32) s32 @public @arbitraryArgs {
return arbitraryArgsCount() as s32;
}
fn main() s32 @public {
return countArgs(0, 1, 2, 3);
}
fn sumExtraValues(label: CString) s32 @public @arbitraryArgs {
var args: ptr = arbitraryArgs();
var total: s32 = 0;
var index: usize = 0;
while index < arbitraryArgsCount() {
total += arbitraryArgFrom(args, s32);
index++;
}
return total;
}
fn main() s32 @public {
return sumExtraValues("scores", 10 as s32, 20 as s32, 30 as s32);
}