| ... | @@ -3117,7 +3117,50 @@ test "error union" { | ... | @@ -3117,7 +3117,50 @@ test "error union" { |
| 3117 | comptime assert(@typeOf(foo).ErrorSet == error); | 3117 | comptime assert(@typeOf(foo).ErrorSet == error); |
| 3118 | } | 3118 | } |
| 3119 | {#code_end#} | 3119 | {#code_end#} |
| 3120 | <p>TODO the <code>||</code> operator for error sets</p> | 3120 | {#header_open|Merging Error Sets#} |
| | 3121 | <p> |
| | 3122 | Use the <code>||</code> operator to merge two error sets together. The resulting |
| | 3123 | error set contains the errors of both error sets. Doc comments from the left-hand |
| | 3124 | side override doc comments from the right-hand side. In this example, the doc |
| | 3125 | comments for <code>C.PathNotFound</code> is <code>A doc comment</code>. |
| | 3126 | </p> |
| | 3127 | <p> |
| | 3128 | This is especially useful for functions which return different error sets depending |
| | 3129 | on {#link|comptime#} branches. For example, the Zig standard library uses |
| | 3130 | <code>LinuxFileOpenError || WindowsFileOpenError</code> for the error set of opening |
| | 3131 | files. |
| | 3132 | </p> |
| | 3133 | {#code_begin|test#} |
| | 3134 | const A = error{ |
| | 3135 | NotDir, |
| | 3136 | |
| | 3137 | /// A doc comment |
| | 3138 | PathNotFound, |
| | 3139 | }; |
| | 3140 | const B = error{ |
| | 3141 | OutOfMemory, |
| | 3142 | |
| | 3143 | /// B doc comment |
| | 3144 | PathNotFound, |
| | 3145 | }; |
| | 3146 | |
| | 3147 | const C = A || B; |
| | 3148 | |
| | 3149 | fn foo() C!void { |
| | 3150 | return error.NotDir; |
| | 3151 | } |
| | 3152 | |
| | 3153 | test "merge error sets" { |
| | 3154 | if (foo()) { |
| | 3155 | @panic("unexpected"); |
| | 3156 | } else |err| switch (err) { |
| | 3157 | error.OutOfMemory => @panic("unexpected"), |
| | 3158 | error.PathNotFound => @panic("unexpected"), |
| | 3159 | error.NotDir => {}, |
| | 3160 | } |
| | 3161 | } |
| | 3162 | {#code_end#} |
| | 3163 | {#header_close#} |
| 3121 | {#header_open|Inferred Error Sets#} | 3164 | {#header_open|Inferred Error Sets#} |
| 3122 | <p> | 3165 | <p> |
| 3123 | Because many functions in Zig return a possible error, Zig supports inferring the error set. | 3166 | Because many functions in Zig return a possible error, Zig supports inferring the error set. |