From d6c43d672687de58df1143dad914c403212247eb Mon Sep 17 00:00:00 2001 From: Alex Kladov Date: Fri, 28 Jun 2024 13:32:56 +0100 Subject: [PATCH] langref: add example for errdefer |err| sytnax --- doc/langref.html.in | 4 ++++ doc/langref/test_errdefer_capture.zig | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 doc/langref/test_errdefer_capture.zig diff --git a/doc/langref.html.in b/doc/langref.html.in index aa606abd69fa..f0b775a04310 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -2988,6 +2988,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.

+

+ The {#syntax#}errdefer{#endsyntax#} statement can optionally capture the error: +

+ {#code|test_errdefer_capture.zig#} {#header_close#} {#header_open|Common errdefer Slip-Ups#}

diff --git a/doc/langref/test_errdefer_capture.zig b/doc/langref/test_errdefer_capture.zig new file mode 100644 index 000000000000..26be5269bdeb --- /dev/null +++ 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