Himujjal
Himujjal

Reputation: 2127

How to initialize variadic function arguments in Zig?

What is the proper way to use and initialise variadic arguments in Zig functions?

fn variadicFunc(val: u8, variadicArg: ...u8) {
  for (variadicArg) |arg| {
    // ... work on the arg
    _ = arg;
  }
}

Upvotes: 2

Views: 5165

Answers (2)

ousttrue
ousttrue

Reputation: 21

It is possible with anytype and @call.

pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
const std = @import("std");

fn call_printf(fmt: [*:0]const u8, args: anytype) c_int {
    return @call(.{}, std.c.printf, .{fmt} ++ args);
}

pub fn main() anyerror!void {
    _ = call_printf("All your codebase are belong to %s.", .{"us"});
}

Upvotes: 2

Himujjal
Himujjal

Reputation: 2127

Answering my own question, thanks to Aiz and Hanna from Zig Discord:

The most basic way to write variadicFunction in Zig is to use anytype and anonymous structs:

fn variadicFunc(variadicArg: anytype) {
  for (std.meta.fields(@TypeOf(items)) |field| {
    const value = @field(items, field.name); 
   // work with the value
  }
}

variadicFunc(.{"Hello", 12, .{ Hello } });

But be careful. This will create a binary bloat. Use arrays or slices whenever possible.

Upvotes: 2

Related Questions