Non zero types like in rust / Explicit value of null?

Are there any types like rusts Non zero ints? Option<NonZero<u32>>. Well it is actually even probably XY problem. I just need to tell the lang: “hey here is a type X and lets say we have ?X. When you see Y value, lets treat it as null for this ?X”

2 Likes

No, that currently does not exist. If T is not a pointer type, ?T is currently implemented as something like

union {
    none: void,
    payload: T,
};
4 Likes

The ranged ints proposal will allow specifying the valid range of a value.

Currently the best way of doing this is with a enum:

const Thing = enum(u32) {
    null = 0,
    _,
};
6 Likes

As of yet, no. The way you might do it right now is with a non-exhaustive enum:

const E = enum(u32) {
    null = 0,
    _,
};

But it is not exactly the same thing and while you can use null as a field name, it’s not the same as an optional’s null – when using it, you’d still write .null with a dot prepended. (And it doesn’t work with .? and orelse)


Doing what you have in mind would require two things to be done:


EDIT: Lol, we certaily did pile onto this question, @leecannon, @alanza :grin:

3 Likes

So I assume there is no any hacks I can cast existing u32 with 0 denoting null to actual ?u32 without spraying everywhere with something like this:

return if(value == 0) null else value; 

To just then be able to do sugary if(value) |value|?

Most you could probably do is something like this (may contain typos, didn’t try to compile):

const E = enum(u32) {
    null = 0,
    _,

    fn unwrap(self: E) ?u32 {
        return switch (self) {
            .null => null,
            else => @intFromEnum(self), // or `@backingInt(self)` on Zig master
        };
    }
};

I’ve used something like this in the past in my game, but in my case I didn’t really need the optionals-specific syntax, so I ultimately got rid of it.

7 Likes