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
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.