Skip to content

Assert compile error for unspecified array/slice format #7675

@marler8997

Description

@marler8997

I'm opening an issue based on my comment here: #6870 (comment)

That PR was just merged which means that now the default format for printing slices/arrays will be integer values rather than raw values, i.e.:

const std = @import("std");
pub fn main() void {
    std.debug.warn("Hello, {}\n", .{"World"});
}
$ zig run hello.zig
Hello, [5:0]u8@7ff7cb1be3a0

The fix for this example is to specify {s} whenever you're printing a string. The problem with this is now whenever a format string does not specify the correct format, the bug will not be caught until runtime and the string is inspected. What makes this worse is that this kind of format string is commonly used for error messages, which often don't get tested or inspected until the error occurs, which many times is only seen rarely if at all. There is now a disconnect between what code looks like, and the default way to format strings.

To remedy this, I propose that we require a format specifier for slices/arrays. On top of that, in order to support generic code I propose that we enable today's current behavior of {} with an explicit specifier. Something like {any}. The {any} specifier would mean "print this thing, I'm not picky about the exact format, just print it somehow". The difference here is that instead having this "I'm not picky about the format" attitude by default with {}, the user has to opt-in to it.

Also note that with the PR that was just merged, alot of Zig code will now be broken due to missing format specifiers that were meant to be {s}. Implementing this proposal means these bugs will be found at compile-time so they will be easy to find and fix.

Here's the list of array specifiers:

{s} - format as a list of Unicode characters characters and interpret array as a utf8 encoded string
{d} - format as a list of decimal values
{x} - format as a list of lowercase hex values
{X} - format as a list of uppercase hex values

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.standard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions