Here is the original code:
const std = @import("std");
fn retEight() !u8 {
return 8;
}
pub fn main() !void {
if (retEight()) |val| {
std.debug.print("{}", .{val});
} else {
std.debug.print("{}", .{42});
}
}
Here is what I get:
zig run main.zig
main.zig:8:17: error: expected optional type, found '@typeInfo(@typeInfo(@TypeOf(main.retEight)).Fn.return_type.?).ErrorUnion.error_set!u8'
if (retEight()) |val| {
~~~~~~~~^~
referenced by:
callMain: /Users/timfayz/zig/lib/std/start.zig:608:32
initEventLoopAndCallMain: /Users/timfayz/zig/lib/std/start.zig:542:34
remaining reference traces hidden; use '-freference-trace' to see all reference traces
What I was actually supposed to do is to add |_| in the else to make things going. Or formally, since I used the payload capturing in the if part, the control structure is probably expecting the error capturing part. However, the error message says that zig expected optional type but I already provided it exactly in the place it is referring to! retEight() is of type !u8.
Could anyone explain the logic behind this error message and how a developer is supposed to read it in order to fix the error? 🥲