Skip to content

Instantly share code, notes, and snippets.

@Hirrolot
Created January 18, 2022 19:48
Show Gist options
  • Save Hirrolot/8f47529ffd98ef536f43e66407857dc2 to your computer and use it in GitHub Desktop.
Save Hirrolot/8f47529ffd98ef536f43e66407857dc2 to your computer and use it in GitHub Desktop.
Generic `printf` implementation in Zig
const std = @import("std");
fn printf(comptime fmt: []const u8, args: anytype) anyerror!void {
const stdout = std.io.getStdOut().writer();
comptime var arg_idx: usize = 0;
inline for (fmt) |c| {
if (c == '*') {
try printArg(stdout, args[arg_idx]);
arg_idx += 1;
} else {
try stdout.print("{c}", .{c});
}
}
comptime {
if (args.len != arg_idx) {
@compileError("Unused arguments");
}
}
}
fn printArg(stdout: std.fs.File.Writer, arg: anytype) anyerror!void {
if (@typeInfo(@TypeOf(arg)) == .Pointer) {
try stdout.writeAll(arg);
} else {
try stdout.print("{any}", .{arg});
}
}
pub fn main() !void {
try printf("Mr. John has * contacts in *.\n", .{ 42, "New York" });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment