j_k*_*non 6 command-line-arguments zig
语境
对这门语言非常陌生,所以请耐心等待。我正在编写一个超级基本函数来打印传递给程序的命令行参数。这是关键逻辑:
// already created allocator (std.heap.ArenaAllocator) and iterator (std.process.ArgIterator)
var idx: u16 = 0;
while (true) {
var arg = iterator.next(&allocator.allocator) catch |err| {
// ...
};
if (arg == null) {
print("End of arguments, exiting.", .{});
break;
}
print("Argument {d}: {s}", .{idx, arg});
idx += 1;
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到一条错误消息:
error: expected error union type, found '?std.process.NextError![:0]u8'
var arg = iterator.next(&allocator.allocator) catch |err| return err;
Run Code Online (Sandbox Code Playgroud)
NextError我认为这个问题与返回可选错误联合的事实有关。但我不能确定,因为我还没有找到任何涵盖此特定案例的文档。
问题
我通过删除捕获并假装返回类型的错误部分不存在来使此代码正常工作。但问题是,捕获该错误的正确方法是什么?
您需要使用它.?或将其放入else捕获中:
if (arg == null) {
print("End of arguments, exiting.", .{});
break;
}
print("Argument {d}: {s}", .{idx, arg.?});
idx += 1;
Run Code Online (Sandbox Code Playgroud)
if (arg) |a| {
print("Argument {d}: {s}", .{idx, a});
idx += 1;
} else {
print("End of arguments, exiting.", .{});
break;
}
Run Code Online (Sandbox Code Playgroud)