Variadic Functions (v0.2.2)

Functions that accept a variable number of arguments.

Latest

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.

Supported Types

arbitraryArgFrom only accepts scalar and pointer types.

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);
}

Back to language reference