Switch on type 'anyerror!f32'

Hey guys, I’m learning Zig and I’m running into the error issue. That’s great, but I don’t understand. Are they handled as types? Or am I misinterpreting the error the compiler is giving me? I’m using Zig 0.15.1.

const std = @import("std");
const print = std.debug.print;

const Error = error{DivitionError};

pub fn divition(numerator: f32, denominator: f32) anyerror!f32 {
    if (denominator == 0.0) {
        return Error.DivitionError;
    }
    return numerator / denominator;
}

pub fn main() void {
    const result = divition(1.0, 0.0);
    switch (result) {
        Error.DivitionError => print("Division failed: An error ocurrited xd", .{}),
        else => print("Result: {}\n", .{result}),
    }
}

You need a try or a catch to handle the error, so that result contains just the f32 and not the error union return by divition.

You don’t need anyerror (it is rarely used). Instead use either !f32 or error{DivitionError}!f32 as the return type.

(Division is spelled with an “s” not a “t”.)

2 Likes

Thank you very much, I will keep that in mind.

2 Likes