Skip to content

Commit 8267929

Browse files
matkladandrewrk
authored andcommitted
langref: add example for errdefer |err| sytnax
1 parent aa73bb6 commit 8267929

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

doc/langref.html.in

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2992,6 +2992,10 @@ fn createFoo(param: i32) !Foo {
29922992
the verbosity and cognitive overhead of trying to make sure every exit path
29932993
is covered. The deallocation code is always directly following the allocation code.
29942994
</p>
2995+
<p>
2996+
The {#syntax#}errdefer{#endsyntax#} statement can optionally capture the error:
2997+
</p>
2998+
{#code|test_errdefer_capture.zig#}
29952999
{#header_close#}
29963000
{#header_open|Common errdefer Slip-Ups#}
29973001
<p>

doc/langref/test_errdefer_capture.zig

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const std = @import("std");
2+
3+
fn captureError(captured: *?anyerror) !void {
4+
errdefer |err| {
5+
captured.* = err;
6+
}
7+
return error.GeneralFailure;
8+
}
9+
10+
test "errdefer capture" {
11+
var captured: ?anyerror = null;
12+
13+
if (captureError(&captured)) unreachable else |err| {
14+
try std.testing.expectEqual(error.GeneralFailure, captured.?);
15+
try std.testing.expectEqual(error.GeneralFailure, err);
16+
}
17+
}
18+
19+
// test

0 commit comments

Comments
 (0)