authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2020-07-08 00:53:19-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-08 19:32:15+00:00
logf77c968cf841046238eb37f54600cda201f09ce2
tree49221c678e9037ec5f305ebac52dcf3c64e069f5
parenteeae3a8f9df49e53392bcd7b04b463f6bffcec9c

langref: Add test case for "if error union with optional"

This is an edge case that isn't too uncommon but is rather confusing to try to deduce without documentation, since it feels like `else` is being overloaded in this scenario and there's no obvious 'correct' behavior here. This just adds a test demonstrating how Zig currently behaves in this scenario.

1 files changed, 26 insertions(+), 0 deletions(-)

doc/langref.html.in+26
...@@ -3861,6 +3861,32 @@ test "if error union" {...@@ -3861,6 +3861,32 @@ test "if error union" {
3861 unreachable;3861 unreachable;
3862 }3862 }
3863}3863}
3864
3865test "if error union with optional" {
3866 // If expressions test for errors before unwrapping optionals.
3867 // The |optional_value| capture's type is ?u32.
3868
3869 const a: anyerror!?u32 = 0;
3870 if (a) |optional_value| {
3871 assert(optional_value.? == 0);
3872 } else |err| {
3873 unreachable;
3874 }
3875
3876 const b: anyerror!?u32 = null;
3877 if (b) |optional_value| {
3878 assert(optional_value == null);
3879 } else |err| {
3880 unreachable;
3881 }
3882
3883 const c: anyerror!?u32 = error.BadValue;
3884 if (c) |optional_value| {
3885 unreachable;
3886 } else |err| {
3887 assert(err == error.BadValue);
3888 }
3889}
3864 {#code_end#}3890 {#code_end#}
3865 {#see_also|Optionals|Errors#}3891 {#see_also|Optionals|Errors#}
3866 {#header_close#}3892 {#header_close#}