Skip to content

String formatting requiring alignment when specifying fill character is surprising #13932

Open
@tobbez

Description

@tobbez

Many users coming from other languages (such as Python, Rust, and even C to some extent) would (not unreasonably, given prior experience with other languages) expect the following code:

std.log.info("'{:02}'", .{1});

to print '01', but because Zig requires alignment to be specified when specifying a fill character, it will instead print ' 1'. The code that would do what the user expected in this case is:

std.log.info("'{:0>2}'", .{1});

This mismatch is likely to produce bugs and confuse users (until they find the appropriate documentation).

The current behavior is not necessarily wrong for Zig, but it would make sense to at least consider whether some change in behavior is warranted.

Note that this isn't a purely theoretical concern, as it has already happened at least once in practice.

I searched for prior discussions on this topic, but only found a single comment that also found the current behavior unexpected and offered two ideas for improvements (along with code implementing them): produce a compile error on leading zeros in the width parameter, or honor unambiguous fill characters even without alignment.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSolving this issue will likely involve adding new logic or components to the codebase.standard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions