Created
May 17, 2024 12:09
-
-
Save hippietrail/c2cb700b7f5b9f1403d5e69a8bbd6eef to your computer and use it in GitHub Desktop.
Minimal Zig of a custom formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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