Skip to content

Instantly share code, notes, and snippets.

@hippietrail
Created May 17, 2024 12:09
Show Gist options
  • Save hippietrail/c2cb700b7f5b9f1403d5e69a8bbd6eef to your computer and use it in GitHub Desktop.
Save hippietrail/c2cb700b7f5b9f1403d5e69a8bbd6eef to your computer and use it in GitHub Desktop.
Minimal Zig of a custom formatter
const std = @import("std");
pub fn main() void {
var foo: ?u64 = 101;
std.debug.print("optional u64 foo = '{}'\n", .{optionalU64(foo)});
foo = null;
std.debug.print("optional u64 foo = '{}'\n", .{optionalU64(foo)});
foo = 1000000;
std.debug.print("optional u64 foo = '{}'\n", .{optionalU64(foo)});
}
fn formatOptionalU64(val: ?u64, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
if (val) |v| try writer.print("{d}", .{v});
}
fn optionalU64(val: ?u64) std.fmt.Formatter(formatOptionalU64) {
return .{ .data = val };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment