#else prong required when switching on pointer type

1 messages · Page 1 of 1 (latest)

digital roost
#

Hi, I'm learning zig and I've found a confusing error when doing a switch on a pointer to a tagged union.

I need to access the union through a pointer because sometimes I need to mutate one of the inner fields of the union and other times I want to change to a different tag.

I've constructed a somewhat non-sensical example:

const Foo = union(enum) {
    a: u8,
    b,
};

pub fn main() !void {
    var foo: Foo = .b;

    while (true) {
        switch (&foo) {
            .a => |a| {
                a.* += 1;
            },
            .b => {
                foo = Foo{ .a = 0 };
            },
        }
    }
}

And then when running:

$ zig run wtf.zig
wtf.zig:10:9: error: else prong required when switching on type '*wtf.Foo'

shell returned 1

Why do I need an else branch on the switch? Is this avoidable?

fleet viper
#

when you need to switch on a pointer type, just do switch(ptr.*) { ...

idle herald
#

an else branch is required because youre switching on the value of the pointer, youre comparing address it contains, not the variant of what its pointing to

#

and your switch doesn’t have a prong for every single possible address, so it needs an else :P