I come from a Java/Scala/Python background and am used to providing additional error information via an exception object that is raised/thrown. I did a search and found the following link:
I am using Zig 15-dev and if fails to compile. I am assuming there have been changes that don’t allow this. What is the idiomatic way to do this? I was thinking of using a pointer to a parameter, but this means dragging this through all the functions. I would also like to avoid the use of global variables.
and use this as the sole return value of your functions as a makeshift error union.
But make sure that context doesn’t go out of scope as soon as your function returns (you could make it comptime).
Only Zig errors can occur to the left of the !. They cannot be a struct with a payload. One way to do this is return the error code as zig usual and have an out-parameter for the error payload. This can receive a pointer for something dynamically allocated by your function, in which case the caller is responsible for deallocating it, or the caller can pass the address of an error payload struct that is filled by your function – which can live where you choose – could be a global or some other app-wide context, or a local in just the caller. Or, you can use the single result value tagged union approach.
I am guessing that it’s likely best to separate ok result from error result so that your main result data flow isn’t carrying around error information.
This is commonly referred to as the “Diagnostics” pattern. There are several examples in Zig’s stdlib. Here’s one for std.json: std.json.Diagnostics.
@pachde and @00JCIV00
So the “diagnostics pattern” uses a local variable solution, which has the advantage of not requiring memory allocation and free. Seems doable. May be the simplest option for me.
@Justus2308 I have been looking at this carefully, and it looks like an interesting but more complex alternative to the “diagnostics pattern”. The use of comptime to avoid loss of scope is interesting.