#Can someone explain the syntax of the 'optional if' ?
1 messages · Page 1 of 1 (latest)
i believe its called a "closure", and does exist in other languages
I have only heard the term closures, Looks like I have to learn about it now
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
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
yeah i looked it up and it doesn't match
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;
// ...
}
it can also be used for errors
yes, but with an error the else-branch is mandatory
ye
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
why do we need to assign the value of the variable used to check the condition(a) into another variable(value) can't we just use the variable(a)
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
so you are saying the variable(a) can be null in runtime and we are checking if it is null or not?
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
so in this while loop are we checking if(iter) can iterate once more using(.next()) and if it can are we assigning the iterated value to the variable(value)?