Open Darkfllame opened 1 week ago
Two notes:
.!
used to be in the language iirc, but was removed in order to encourage the longer catch unreachable
.
This is to make these places stick out more to readers - simply asserting no error is possible is usually a code smell / sign of .
IMO it's better style to instead switch on the error and comment for every case why it is guaranteed to be unreachable in this scenario,
so that newly added errors lead to a missing switch case compile error,
and if an error does get hit unexpectedly, it becomes easier to compare the commented reasoning against the scenario that did trigger the error.comptime
argument of []const u8
using @field
.
I think the reason it's not in the language already is that a.b.c orelse
will silently change code behavior if field b
is changed into an optional later on, even if this wasn't the intention when writing the code.
The majority of current Zig semantics promote compile errors to add friction any time a structural change like this happens, so that someone reviews all affected places in code.
(Just pointing out the current philosophy, not saying we couldn't/shouldn't provide users a choice in this matter.)making it easier to do catch unreachable
is something we explicitly do not want to be encouraged
zig's optionals are really useful in a lot of situations, and they really are good features of it, however sometimes it can be a little tricky to work with them, but today I want to pin point the way to handle those.
So first off, the current way of unwrapping an error is with the
catch unreachable
syntax, but optionals can be unwrapped with the.?
so I first propse to add a.!
syntax or to remove the.?
syntax of optionals (which is surely not happening).Now, the
.?
syntax is fine as it is, but it becomes annoying when working with optionals structs containing optional values, optional slices (sometimes, interfacing with C APIs for example), etc... so I would like to propose a way to "upgrade" theorelse
syntax and field accessing:Notes:
.!
syntax is added to the language, the same proposal applies to it too (except, usescatch
instead oforelse
).orelse
/catch
after, still results in a panic just as before.@TypeOf(nestedVar.optionalField2.optionalField3) = ?u32
Additional use cases:
function.?() orelse { . . . }
&myNullableValue.? orelse null
instead of&(myNullableValue orelse retur null)