How to propertly write a format function for a user type?

Hi all,

In the standard library documentation for std.fmt.format it mentioned the following:

/// If a formatted user type contains a function of the type
/// ```
/// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void
/// ```
/// with `?` being the type formatted, this function will be called instead of the default implementation.
/// This allows user types to be formatted in a logical manner instead of dumping all fields of the type.

My question is, does anyone have an example of implementing this function for your own type like a union for example?

I don’t know if I’m using it the right way, but it’s worked fine for me using it like this:

pub const Token = struct{
    offset: usize,
    src: ?[]const u8,
    ty: Type,

    pub fn format(
        self: Token,
        comptime fmt: []const u8,
        options: std.fmt.FormatOptions,
        writer: anytype
    ) !void {
        // Need to do this to avoid unused function param errors.
        // Maybe there's a better way?
        _ = fmt;
        _ = options;

        _ = try writer.print(
            "Token{{ type: {}, offset: {}",
            .{ self.ty, self.offset }
        );

        if (self.src) |src| _ = try writer.print(", src: '{s}'", .{src});

        try writer.writeAll(" }");
    }
};
1 Like

Thank you! That’ll work!

1 Like