admin管理员组

文章数量:1127588

I'm new to Zig and have been going through some premade exercises to get a hang of it. I got stuck on one because I misunderstood what the compiler was trying to tell me.

I've mocked up a sample of what happened. See comments on fn memo and the first try map.put.

If I wanted to have the function memo as returning u32 and not !u32, how would I best change the contents of the function to allow me to do that?

const hm = std.StringHashMap(u32);

pub fn main() !void {
    const s = "ABC";
    const val = try memo(s);
}

fn memo(s: []const u8) !u32 {  // If this is just u32 and not !u32 then
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer {
        _ = gpa.deinit();
    }
    const alloc = gpa.allocator();
    var map = HM.init(alloc);
    defer map.deinit();

    try map.put("A", 1); // "Error expected type 'u32' found 'error{OutOfMemory}'"
    try map.put("B", 2);
    try map.put("C", 3);

    var total: u32 = 0;
    for (s) |c| {
        const ch = [1]u8{c};
        const val = map.get(&ch);

        total += val.?;
    }
    return total;
}

本文标签: error handlingHow to override Zig Function Return (eg u32 vs u32) Compile BehaviorStack Overflow