zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 82679297422d02039c992cc223f5cfbf6fcd8675 (tree)
parent aa73bb6bc969ef053a8fab265da8bf28e024b2d2
Author: Alex Kladov <aleksey.kladov@gmail.com>
Date:   Fri, 28 Jun 2024 13:32:56 +0100

langref: add example for errdefer |err| sytnax

Diffstat:
Mdoc/langref.html.in | 4++++
Adoc/langref/test_errdefer_capture.zig | 19+++++++++++++++++++
2 files changed, 23 insertions(+), 0 deletions(-)

diff --git a/doc/langref.html.in b/doc/langref.html.in @@ -2992,6 +2992,10 @@ fn createFoo(param: i32) !Foo { the verbosity and cognitive overhead of trying to make sure every exit path is covered. The deallocation code is always directly following the allocation code. </p> + <p> + The {#syntax#}errdefer{#endsyntax#} statement can optionally capture the error: + </p> + {#code|test_errdefer_capture.zig#} {#header_close#} {#header_open|Common errdefer Slip-Ups#} <p> diff --git a/doc/langref/test_errdefer_capture.zig b/doc/langref/test_errdefer_capture.zig @@ -0,0 +1,19 @@ +const std = @import("std"); + +fn captureError(captured: *?anyerror) !void { + errdefer |err| { + captured.* = err; + } + return error.GeneralFailure; +} + +test "errdefer capture" { + var captured: ?anyerror = null; + + if (captureError(&captured)) unreachable else |err| { + try std.testing.expectEqual(error.GeneralFailure, captured.?); + try std.testing.expectEqual(error.GeneralFailure, err); + } +} + +// test