#Can someone explain the syntax of the 'optional if' ?

1 messages · Page 1 of 1 (latest)

grim galleon
#

I don't understand why there is an '|value|' after 'if(a)' . Is this something specific to zig or does other languages have it? I haven't seen it anywhere else.

iron citrus
grim galleon
fickle lynx
#

it can seem a bit pointless when just using it on variables since you could just reuse the variable but i think it shines with functions that return optionals, e.g. mem.split and mem.tokenize iterators in the stdlib. each time you call .next() it either returns null or the next slice and then moves the internal index forward, if you were to do something like if (it.next() != null) that value would be lost

#

so instead you do if (it.next()) |value| and value is the slice that the iterator returned

honest nexus
#

it's not called a closure, a closure is a completely different concept

#

we call the thing in the | a captured value or a payload, you usually see this concept in other languages in the form of pattern matching

grim galleon
honest nexus
#

for example in Rust

if let Some(value) = a {
    // ...
}```
#

Zig does not have pattern matching

#

but some common shorthands are still very useful

#

so you'll see this construct to unwrap values

#

really it's just syntax sugar

#
if (a) |value| {
    // ...
}

// is the same as

if (a != null) {
    const value = a orelse unreachable;
    // ...
}
fickle lynx
#

it can also be used for errors

honest nexus
#

yes, but with an error the else-branch is mandatory

fickle lynx
#

ye

honest nexus
#

which is the key difference

#

you'll see it in a while loop too

var iter = make_some_iterator();
while (iter.next()) |value| {
    // ...
}

// is really just

while (true) {
    const value = iter.next() orelse break;
    // ...
}
#

just making some common patterns more digestible

grim galleon
honest nexus
#

a is a ?T and you cannot use the optional value as if it was T unlike in some languages like javascript

#

there is no concept of nullability

#

you introduce it by making a type optional

#

you can't interact with the value that may or may not exist without handling the possibility of it being null

grim galleon
honest nexus
#

yes. you can't just use a as-is if it has the potential to be null

#

you must handle the case of it being null, for example, with the if-statement construct

#

and if it isn't, then you have access to the value named by the identifier in the |s

#

it may help to read the language reference

#

here's the part that covers optional types

grim galleon
honest nexus
#

yes, in this hypothetical example, next() returns some optional type. so if the type is non-null then the variable, yes, gets assigned to value

#

otherwise the loop is over