struct - 在 Zig 中实现基本的经典 try-catch

标签 struct segmentation-fault zig

如何在 Zig 中实现经典的 try-catch 错误处理?

例如。如何解决这个错误并且只有在没有错误发生时才执行append

var stmt = self.statement() catch {
    self.synchronize(); // Only execute this when there is an error.
};
self.top_level.statements.append(stmt); // HELP? This should only be executed when no error

// ...
fn synchronize() void {
  // ...implementation
}

fn statement() SomeError!void {
  // ...implementation
}

如果可能,请显示上述代码的修改版本。

最佳答案

尝试使用 if-else,如下所示:

if (self.statement()) |stmt| {
   // HELP? This should only be executed when no error
   self.top_level.statements.append(stmt)
} else |error| {
  // Only execute this when there is an error.
  self.synchronize()
}

您可以了解有关 if in the zig documentation 的更多信息

关于struct - 在 Zig 中实现基本的经典 try-catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67034314/

相关文章:

之字号 `Segmentation fault at address`

libpq - 如何为 PQexecParams 的 paramValues 创建类型 '[*c]const [*c]const u8'

c - 为什么我不能对 C 中的 malloced 结构使用部分结构初始化

将数组的变量复制到另一个数组,该数组是带有字符的结构

c - 制作我自己的 strlen 函数,以接收字符串作为链接列表

C - 从字符串中提取所有数字

zig - 仅在特定程序中将转换后的 u8(来自 i8)追加到 ArrayList 时出错

c - 从结构 "Invalid read/write"中的指针获取数据

c++ - 如何修复 C++ 中的运行时错误,它通过了除 1 之外的所有测试用例

c - 为什么 MPI_SEND 在我的 for 循环中不起作用?如果明确说明,它可以正常工作