One method declaration; two Zig annoyances

submited by
Style Pass
2024-11-21 11:30:04

In the following code, we create a Post structure with a skeleton format method. Despite being pretty comfortable with Zig, I could stare at this code for hours and not realize that it has two issues.

I've moaned about this before, but Zig is strict about disallowing shadow declaration. Here we're seeing the error because a function and one of its parameters have the same name. Because every Zig file is an implicit structure, you'll run into this error pretty often (at least I do). For example, if you const socket = @import("socket.zig"), you can forget about using the socket identifier throughout your file.

Our Post struct is now valid; our code compiles and runs. Of course, we're not doing anything yet, so let's make a small addition:

This outputs "## Hello", but we're really close to a more subtle compiler error. If we change the last line to print our post (using the {any} format specifier):

In a previous blog post we purposefully defined a format method to control how our structure is formatted. In another post, we learned about std.meta.hasMethod, which is how Zig's fmt package detects the presence of the format method.

Leave a Comment