Error union payload 'u64' cannot cast into error union payload '?u64' -- what?

pub const AnySeeker = struct {
    context: ?*anyopaque,
    getEndPosFn: ?*const fn (self: ?*anyopaque) anyerror!u64,

    pub inline fn getEndPos(self: AnySeeker) anyerror!?u64 {
        return (self.getEndPosFn orelse return null)(self.context);
    }
};

When the getEndPos function is called, the following error appears:

stream.zig:26:53: error: expected type 'anyerror!?u64', found 'anyerror!u64'
stream.zig:26:53: note: error union payload 'u64' cannot cast into error union payload '?u64'
stream.zig:25:54: note: function return type declared here
stream.zig:332:70: note: called from here

How can this be? Doesn’t u64 coerce to ?u64?

I think you need to try the call the inferred cast fails due to the error union

2 Likes

One function returns anyerror!?u64, another ``anyerror!u64`. They do not coerce.

The error message is not the best here, unfortunately. Apparently, the “cannot cast” here refers to the fact that u64 is not in-memory coercible to ?u64, unlike (for example, depending on the target) c_ulonglong. There’s an open proposal to drop the “in-memory” part of this restriction: Proposal: allow coercions between optionals and error unions with compatible payloads · Issue #16765 · ziglang/zig · GitHub

2 Likes