| ... | @@ -4959,6 +4959,20 @@ fn deferUnwindExample() void { | ... | @@ -4959,6 +4959,20 @@ fn deferUnwindExample() void { |
| 4959 | test "defer unwinding" { | 4959 | test "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. |
| | 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; |
| 4962 | | 4976 | |
| 4963 | // The errdefer keyword is similar to defer, but will only execute if the | 4977 | // 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 | } |
| 4979 | | 4993 | |
| 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 | } |