How to print struct with strings

Here’s an example of implementing std.fmt.format to make a struct printable as @desttinghim mentioned:

 cat src/main.zig
const std = @import("std");

const Product = struct {
    id: i32,
    title: []const u8,
    description: []const u8,
    images: []const []const u8,

    pub fn format(
        product: Product,
        comptime _: []const u8,
        _: std.fmt.FormatOptions,
        writer: anytype,
    ) !void {
        try writer.writeAll("Product{\n");
        _ = try writer.print("\tid: {},\n", .{product.id});
        _ = try writer.print("\ttitle: {s},\n", .{product.title});
        _ = try writer.print("\tdescription: {s},\n", .{product.description});
        try writer.writeAll("\timages: [\n");

        for (product.images) |image| _ = try writer.print("\t\t{s},\n", .{image});

        try writer.writeAll("\t],\n");
        try writer.writeAll("}\n");
    }
};

pub fn main() !void {
    const p = Product{
        .id = 1,
        .title = "Zed Plushy",
        .description = "Cool Zed",
        .images = &.{
            "Image 1",
            "Image 2",
            "Image 3",
        },
    };

    // Now you can print with {} format specifier.
    std.debug.print("{}\n", .{p});
}
❯ zig build run
Product{
	id: 1,
	title: Zed Plushy,
	description: Cool Zed,
	images: [
		Image 1,
		Image 2,
		Image 3,
	],
}
7 Likes