I wish we had union(error) as a first class citizen in Zig.
Yes, I know, each payload has its requirements for init/deinit and Zig can't magically handle that, I know.
But, it can be solved if the caller is forced to handle a function that returns a union(error) or popup exactly the same type. No inferred errors should be allowed for this use case. This way, the caller is always responsible to clean up any resources a payload uses (e.g call payload.deinit();)
Example:
pubconstCustomError=union(error){SimpleError:void,ErrorWithPayload:[]constu8,};pubfnadd_one(number:u64)CustomError!u64{if(number==42){returnCustomError{.ErrorWithPayload="bad number encountered"};}else{returnnumber+1;}};//Correct usagepubfnuse_it_handling_the_error()void{_=add_one(42)catch|err|switch(err){.ErrorWithPayload=>|payload|std.debug.print("errored with payload: {s}! \n",.{payload}),_=>std.debug.print("errored a simple error!\n",.{}),};}//Another correct usagepubfnuse_it_returning_the_same_error()CustomError!void{_=tryadd_one(42);}//Incorrect usage (compiler error)pubfnuse_it_inferring_the_error()!void{_=tryadd_one(42);}
PS: Yes, we can do that in user land already, but without being able to use try/catch.
pubconstCustomResult=union(enum){Success:u64,SimpleError:void,ErrorWithPayload:[]constu8,};pubfnadd_one(number:u64)CustomResult{if(number==42){returnCustomResult{.ErrorWithPayload="bad number encountered"};}else{returnCustomResult{.Success=number+1};}};
For further actions, you may consider blocking this person and/or reporting abuse
I wish we had
union(error)
as a first class citizen in Zig.Yes, I know, each payload has its requirements for init/deinit and Zig can't magically handle that, I know.
But, it can be solved if the caller is forced to handle a function that returns a
union(error)
or popup exactly the same type. No inferred errors should be allowed for this use case. This way, the caller is always responsible to clean up any resources a payload uses (e.g callpayload.deinit();
)Example:
PS: Yes, we can do that in user land already, but without being able to use try/catch.