Skip to content

Commit 09cc6b4

Browse files
perilloandrewrk
authored andcommitted
langref: improve the defer section
Split the original `defer.zig` doctest into 3 doctest: 1. Document the defer keyword 2. Document that the return statement is not allowed inside a defer expression 3. Document the errdefer keyword Replace "method" with "expression" in the text `defer method`.
1 parent e0ba8b8 commit 09cc6b4

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

doc/langref.html.in

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4959,6 +4959,20 @@ fn deferUnwindExample() void {
49594959
test "defer unwinding" {
49604960
deferUnwindExample();
49614961
}
4962+
{#code_end#}
4963+
{#code_begin|test_err|cannot return from defer expression#}
4964+
// Inside a defer expression the return statement is not allowed.
4965+
fn deferInvalidExample() !void {
4966+
defer {
4967+
return error.DeferError;
4968+
}
4969+
4970+
return error.DeferError;
4971+
}
4972+
{#code_end#}
4973+
{#code_begin|test|errdefer#}
4974+
const std = @import("std");
4975+
const print = std.debug.print;
49624976

49634977
// The errdefer keyword is similar to defer, but will only execute if the
49644978
// scope returns with an error.
@@ -4977,19 +4991,6 @@ fn deferErrorExample(is_error: bool) !void {
49774991
print("encountered an error!\n", .{});
49784992
}
49794993

4980-
// inside a defer method the return statement
4981-
// is not allowed.
4982-
// The following lines produce the following
4983-
// error if uncomment
4984-
// ```
4985-
// defer.zig:73:9: error: cannot return from defer expression
4986-
// return error.DeferError;
4987-
// ```
4988-
//
4989-
//defer {
4990-
// return error.DeferError;
4991-
//}
4992-
49934994
if (is_error) {
49944995
return error.DeferError;
49954996
}

0 commit comments

Comments
 (0)