ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
32.23k stars 2.35k forks source link

Proposal: Better optional and errors #20483

Open Darkfllame opened 1 week ago

Darkfllame commented 1 week ago

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" the orelse syntax and field accessing:

const NestedOptionals = struct {
    optionalField: ?u32,
    optionalField2: ?struct {
        optioanlField3: ?f32,
    },
};

pub fn main() void {
    var nestedVar = NestedOptionals{
        .optionalField = 5,
        .optionalFild2 = null,
    };
    // "old" style unwrapping works as expected
    const myField = nestedVar.optionalField.?;
    // orelse work same as before
    const myField2 = nestedVar.optionalField orelse 0;

    // now, I propose unwrapping chaining
    const myField3 = nestedVar.optionalField2.optioanlField3 orelse 5;
    // extends to: blk: {
        break :blk (nestVar.optionalField2 orelse break :blk 5).optionalField3 orelse 5
    }
    // myField3 would be 5 in this case
}

Notes:

Additional use cases:

rohlem commented 1 week ago

Two notes:

nektro commented 1 week ago

making it easier to do catch unreachable is something we explicitly do not want to be encouraged