Hey everyone, I’m a relatively new user of Zig with a background in Rust. Currently I’m learning the language step-by-step and it’s quite a smooth ride, however Payload Captures seem like a road-block for now as I can’t figure out what is happening, and unfortunately I can’t find any resources on the internet breaking it down, only examples as to how it’s used.
For now I understand you can do the following:
// Iterating over an array
const msg = "hello";
for (msg) |ltr| {
try expect(ltr > 'a' and ltr < 'z');
}
// Destructuring optionals
var maybe_num: ?usize = 10;
if (maybe_num) |n| {
try expect(n == 10);
}
// With tagged unions (code copied from https://ziglearn.org/chapter-1/#unions)
const Tag = enum { a, b, c };
const Tagged = union(Tag) { a: u8, b: f32, c: bool };
var value = Tagged{ .b = 1.5 };
switch (value) {
.a => |*byte| byte.* += 1,
.b => |*float| float.* *= 2,
.c => |*b| b.* = !b.*,
}
try expect(value.b == 3);
Assuming I’ve understood correctly, these are three examples of payload capturing, however each example is quite different, in that the “meaning” of (variable) |extract|
changes depending on whether it is preceded by switch
, for
or if
. I think what would help a lot is a breakdown of the syntax, something like (if | for | switch) (IDENTIFIER) |IDENTIFIER| { }
that details what’s going on, if something like that makes sense?
From Rust I’m used to pattern destructuring, where any structure can be destructured (arrays, structs, tagged unions) in a consistent way independent of the structure. I guess Payload Capturing does not function analogously? Any information on this topic would help me out I think, the problem is that I can’t find any beginner-friendly information on this topic elsewhere (besides examples). Thanks a lot in advance!
Edit: Just to illustrate my point, if I were to do
if (msg) |ltr| {
try expect(ltr > 'a' and ltr < 'z');
}
Instead in the code above, that would now give me a compile-error saying that msg
must be an optional type, not a u8
array.
As a result I’m left with quite a lot of questions; is if (variable) |extract|
only usable with optionals? Similarly is for (variable) |extract|
only usable with arrays? Are there any other terms (other than if
, for
and switch
) that can precede a (variable) |extract|
? Is all of this syntactic sugar for something else?