Optionals
Optionals use the syntax ?T
and are used to store the data
null
, or a value of type
T
.
Optionals support the orelse
expression, which acts when the optional is
null
. This unwraps the
optional to its child type.
.?
is a shorthand for orelse unreachable
. This is used for when you know it
is impossible for an optional value to be null, and using this to unwrap a
null
value is detectable
illegal behaviour.
Both if
expressions and while
loops support taking optional values as conditions,
allowing you to “capture” the inner non-null value.
Here we use an if
optional payload capture; a and b are equivalent here.
if (b) |value|
captures the value of b
(in the cases where b
is not null),
and makes it available as value
. As in the union example, the captured value
is immutable, but we can still use a pointer capture to modify the value stored
in b
.
And with while
:
Optional pointer and optional slice types do not take up any extra memory
compared to non-optional ones. This is because internally they use the 0 value
of the pointer for null
.
This is how null pointers in Zig work - they must be unwrapped to a non-optional before dereferencing, which stops null pointer dereferences from happening accidentally.