0

I'm learning Zig and

pub fn foo() usize {
    var gpa = std.heap.GeneralPurposeAllocator(.{ .verbose_log = true }){};
    defer std.debug.assert(gpa.deinit() == .ok);
    const allocator = gpa.allocator();

    var map = std.StringHashMap(i32).init(allocator);

    try map.put("example", 0);
}

When I try to compile and run this code, I get the following error:

solution.zig:11:5: error: expected type 'usize', found 'error{OutOfMemory}' try map.put("example", 0); ^~~~~~~~~~~~~~~~~~~~~~~~~

I'm not sure what I'm doing wrong. I am using Zig version 0.13.0

1
  • 1
    as @prokop's answer points out, calling try in a function requires the return type to be an error union, i.e. error or value (cmp. Result in Rust). In addition, note that map.put has return type "error or void" (src), so unless you plan to return some other parameter (usize) from your function, the return type of foo would be !void in your example. Commented Dec 12, 2024 at 10:13

1 Answer 1

2

The rest of the error hints at the problem:

a.zig:10:5: error: expected type 'usize', found 'error{OutOfMemory}'
    try map.put("example", 0);
    ^~~~~~~~~~~~~~~~~~~~~~~~~
a.zig:3:21: note: function cannot return an error
pub export fn foo() usize {
                    ^~~~~

You applied try at the map.put but that is trying to return the error from this function. The compiler is complaining that the function return value is usize but the try needs to return a error{OutOfMemory}

You can fix this by changing the functions return type to error{OutOfMemory}!usize or just !usize (and then returning a usize later in the function).

See the language reference section about the error union type for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.