Zig fmt doesn't handle multiline struct initialization as expected

If I have code that looks like this:

const x: MyStruct = .{
   .a = 1,
   .b = 2,
   .c = 3
};

when I run zig fmt it changes to

const x: MyStruct = .{ .a = 1, .b = 2, .c = 3 };

which is not what I expected after reading zig fmt policy · Issue #1003 · ziglang/zig · GitHub

if the struct initialization spans more than 1 line or has a trailing comma after the last item, zig fmt renders with 1 line per field and a trailing comma

I don’t have the trailing comma, but it does “span more than 1 line”, so why is zig fmt behaving this way? Is this expected or a bug?

1 Like

the docs are wrong, you need the trailing comma. it’s actually much more useful that way since it allows you to toggle between the two modes by adding/removing the comma

4 Likes

(you can also force the behavior by adding a comment)