Spoke with Spex and Andrew and they confirmed that doing switch (self.*) does not create a copy, so you can do this:
switch (self.*)
const Cat = struct { hp: usize, pub fn eat(self: *Cat) void { self.hp += 1; } }; const Animal = union(enum) { cat: Cat, dog: Dog, pub fn eat(self: *Animal) void { switch (self.*) { inline else => |*case| case.eat(), } } };
Diff:
*Cat
*Animal
|*case|
This would not work if self.* created a copy, but since it never does, it's fine.
self.*
If you have *Cat, why would you need self.cat.hp += 1; and not: self.hp += 1;
oh, I forgot to update that line from the original code by Zhora.
I've fixed it now, thank you.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
Take off every Zig!
Spoke with Spex and Andrew and they confirmed that doing
switch (self.*)
does not create a copy, so you can do this:Diff:
*Cat
, not a*Animal
|*case|
and calling the function normallyThis would not work if
self.*
created a copy, but since it never does, it's fine.If you have *Cat, why would you need
self.cat.hp += 1;
and not:
self.hp += 1;
oh, I forgot to update that line from the original code by Zhora.
I've fixed it now, thank you.