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
版权声明:本文标题:error handling - How to override Zig Function Return (e.g. !u32 vs u32) Compile Behavior? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736696105a1948183.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论