DEV Community

Cover image for A Little Panic in Zig
Mustafif
Mustafif

Posted on

A Little Panic in Zig

In Rust there are several ways to handle errors that come from the Result and Option types. A common way to get the inner value is using the unwrap method that either returns the value or panics the program. So how would we implement this function in Zig? Well there are several methods of handling errors in Zig, to keep ours simple we will use an if/else statement.

Let's start with by creating a file called unwrap.zig, and import the standard library and assign it to the constant std.

// unwrap.zig 
const std = @import("std");
Enter fullscreen mode Exit fullscreen mode

We will be using compile time generics in our function, you may also use function type inference if you'd like.

What we expect is a type for our generic T, and an error set in the form anyerror!T where we will return the value T.

pub fn unwrap(comptime T: type, val: anyerror!T) T {}
Enter fullscreen mode Exit fullscreen mode

Inside of the function we will use an if/else statement where the if statement will handle a successful value and the else statement handles the error. In these statements we will need to capture the values using the | | syntax as shown:

if(val) |value|{
   return value;
} else |err|{
   std.debug.panic("Panicked at Error: {any}",.{err});
}
Enter fullscreen mode Exit fullscreen mode

As you can see in our if block we return the successful value we capture as the variable value, while in the else block, we capture the error as the variable err and print it using std.debug.panic.

To test out our function, I have create an error type called MathError with one field called DivideByZero. This is similar to an enum implementing the Error trait in Rust.

const MathError = error{
    DivideByZero
};
Enter fullscreen mode Exit fullscreen mode

Now we can create a function called divide which checks if the denominator is zero, and if it is we return the divide by zero error.

fn divide(comptime T: type, a: T, b: T) MathError!T{
    if (b == 0){
        return MathError.DivideByZero;
    } else {
        return a / b;
    }
}
Enter fullscreen mode Exit fullscreen mode

Lastly we will create our main function where we will try this with a successful result and a result doomed to panic.

If we run our program we get the following result:

$ zig build-exe unwrap.zig 
$ ./unwrap
Result: 6.71641826e-01
thread 52729 panic: Panicked at Error: error.DivideByZero
...
Enter fullscreen mode Exit fullscreen mode

This article was just a fun experiment to try something I use in Rust and try it in Zig. Like in Rust, panicking isn't a good way to handle errors, and in most cases the try keyword in Zig is enough.

Top comments (0)