authorgravatar for manlio.perillo@gmail.comManlio Perillo <manlio.perillo@gmail.com> 2022-12-11 17:40:36+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-12-12 15:09:45-05:00
log09cc6b4b9e76434d734ed131ed48ca849bf8a6ba
tree5e80875ea8f998b39120214e84d012df3ae1e9db
parente0ba8b8ae5237f8b6da1d19c1088f756fd51eb57

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 files changed, 14 insertions(+), 13 deletions(-)

doc/langref.html.in+14-13
...@@ -4959,6 +4959,20 @@ fn deferUnwindExample() void {...@@ -4959,6 +4959,20 @@ fn deferUnwindExample() void {
4959test "defer unwinding" {4959test "defer unwinding" {
4960 deferUnwindExample();4960 deferUnwindExample();
4961}4961}
4962 {#code_end#}
4963 {#code_begin|test_err|cannot return from defer expression#}
4964// Inside a defer expression the return statement is not allowed.
4965fn deferInvalidExample() !void {
4966 defer {
4967 return error.DeferError;
4968 }
4969
4970 return error.DeferError;
4971}
4972 {#code_end#}
4973 {#code_begin|test|errdefer#}
4974const std = @import("std");
4975const print = std.debug.print;
49624976
4963// The errdefer keyword is similar to defer, but will only execute if the4977// The errdefer keyword is similar to defer, but will only execute if the
4964// scope returns with an error.4978// scope returns with an error.
...@@ -4977,19 +4991,6 @@ fn deferErrorExample(is_error: bool) !void {...@@ -4977,19 +4991,6 @@ fn deferErrorExample(is_error: bool) !void {
4977 print("encountered an error!\n", .{});4991 print("encountered an error!\n", .{});
4978 }4992 }
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
4993 if (is_error) {4994 if (is_error) {
4994 return error.DeferError;4995 return error.DeferError;
4995 }4996 }