I'm surprised that the code compiles. Is it intended?

const std = @import("std");

var _: u8 = 7; // Okay!

pub fn main() !void {
    _ = 8;
    std.debug.print("{}\n", .{@"_"}); // 7
}

If the variable declaration is local, then it doesn’t compile. Is it intended to let the global one legal?

1 Like
var _: u8 = 7;

test "keyword variable name" {
    @"_" = 8;
    try std.testing.expectEqual(8, @"_");

    // this is because global is a field of a struct
    var foo: struct { _: u32 } = .{._ = 42 };
    foo._ += 1;
    try std.testing.expectEqual(43, foo._);
}
1 Like

More precisely, var _ is declaration. Personally, I think it has no problem being a field. But when it is a declaration, it may cause some confusions.

I assume you referring to error about variable not been mutated since putting it in local scope causes it.

It’s pretty hard to figure out if it’s actually mutated since it can happen in unused function which was never analyzed. Or access to it can be done with reflection which prevents easy ast only detection of it’s mutations.

No. I mean _ can be used a declaration name.

1 Like

Just look at this post about this syntax :wink:

This is way weirder than I expected.

1 Like

Functions are immutable, so their names can’t be used as L-values, which is better than using _ as mutable variable names.

Yes, this is unambiguous for compilers. But it is just some weird when _ is used as mutable variable declaration names.