Strange Range Syntax

It definitely feels more like a candidate for What's the most cursed Zig you can write?, than a realistic/useful way to use the language, especially because if you for example try and print the range.over[a..b] or use it with anything else that dereferences it, you will likely segfault your program (or read/print garbage).

Still maybe there are obscure cases where it makes sense (that I haven’t thought of), for most purposes I think something like this would be way better (sketch):

const Range = packed struct {
    start:u32,
    len:?u31,

    pub fn closed(start:u32, len:u31) Range {
        return .{ .start = start, .len = len };
    }
    pub fn openEnded(start:u32) Range {
        return .{ .start = start, .len = null };
    }
    pub fn format(self:Range, writer:*std.Io.Writer) !void {
        ...
    }
};
var range:Range = .openEnded(7);

Depending on use case you could even add a step size, possibly even with negative values, for reverse iteration, allowing optional start or end, inclusive or exclusive start/end.

2 Likes