Custom formatting

Below code works but is this a good way to print with custom options?
Are there shorter / better / faster / nicer ways?
Another thing is that my namespace get very polluted when there are a few types in there.
(I need quite a lot of custom formatting in my program).
Tips tricks welcome.

const foo: Foo = .{ .value = 42 };
std.debug.print("{f}", .{ foo.fmt(true) });
const Foo = struct {
    value: i32,

    pub fn fmt(self: Foo, option: bool) Formatter {
        return .{ .foo = self, .option = option };
    }

    pub const Formatter = struct {
        foo: Foo,
        option: bool,

        pub fn format(self: Formatter, writer: *std.io.Writer) std.io.Writer.Error!void {
            try writer.print("{}", .{ self.foo.value });
            if (self.option) {
                try writer.print(" with option", .{});
            }
        }
    };
};

I really like this pattern:
it’s like what you did but the struct is anonymous
(example from a project).

    const FMTForHumans = 
        \\Calories: {}
        \\fat: {}
        \\    of which saturated: {}
        \\carbohydrates: {}
        \\    of which sugars: {}
        \\fiber: {}
        \\protein: {}
        \\salt: {}
        ;

    pub fn formatForHumans(f: Food) struct {
        food: Food,
        pub fn format(
            self: @This(),
            writer: *std.Io.Writer,
        ) std.Io.Writer.Error!void {
            try writer.print(FMTForHumans, self.food.macros);
        }
    } {
        return .{ .food = f };
    }

so in your case with this pattern it would look like this:

const Foo = struct {
    value: i32,

    pub fn fmt(self: Foo, option: bool) struct {
        foo: Foo,
        option: bool,

        pub fn format(self: @This(), writer: *std.io.Writer) std.io.Writer.Error!void {
            try writer.print("{}", .{ self.foo.value });
            if (self.option) {
                try writer.print(" with option", .{});
            }
        }
    } {
          return .{ .foo = self, .option = option };
    }
};
1 Like

ok! that seems a neat idea.

Also check out std.fmt.Alt, which seems at least related to this.

2 Likes

thanks. interesting.