Hacker News new | ask | show | jobs
by infogulch 499 days ago
Can you expand on how errdefer works in zig? I'm not familiar.
2 comments

https://ziglang.org/documentation/master/#errdefer

defer always executes on scope exit, errdefer executes on an error exit. In principle, this is similar to the logic of a try/catch/finally:

  try {
    // whatever
  } catch {
    // errdefer would belong here
  } finally {
    // defer would happen here
  }
Zig has a special / compiler-known ADT for "value OR error". This is similar to Result<T,E> in Rust. Or in C++, e.g., folly::Expected<T,E>.

The Zig one is so special and compiler-blessed that there is special syntax for defer blocks that only run when the function return is an error variant of that result ADT -- errdefer.