3 ms·
In addition to the default formatting in the standard library as mentioned by AndyKelley, adding a function called "format" to your type will override the stand
by AnIdiotOnTheNet 8y ago
In addition to the default formatting in the standard library as mentioned by AndyKelley, adding a function called "format" to your type will override the standard behavior and allow arbitrary custom formatting. see this example from the test case in std.fmt:
const Vec2 = struct {
const SelfType = @This();
x: f32,
y: f32,
pub fn format(
self: SelfType,
comptime fmt: []const u8,
context: var,
comptime Errors: type,
output: fn (@typeOf(context), []const u8) Errors!void,
) Errors!void {
switch (fmt.len) {
0 => return std.fmt.format(context, Errors, output, "({.3},{.3})", self.x, self.y),
1 => switch (fmt[0]) {
//point format
'p' => return std.fmt.format(context, Errors, output, "({.3},{.3})", self.x, self.y),
//dimension format
'd' => return std.fmt.format(context, Errors, output, "{.3}x{.3}", self.x, self.y),
else => unreachable,
},
else => unreachable,
}
}
};
var value = Vec2 {
.x = 10.2,
.y = 2.22,
};
try testFmt("point: (10.200,2.220)\n", "point: {}\n", &value);
try testFmt("dim: 10.200x2.220\n", "dim: {d}\n", &value);