File tree Expand file tree Collapse file tree 3 files changed +66
-1
lines changed Top Open diff view settings Expand file tree Collapse file tree 3 files changed +66
-1
lines changed Top Open diff view settings Original file line number Diff line number Diff line change @@ -3117,7 +3117,50 @@ test "error union" {
31173117 comptime assert(@typeOf(foo).ErrorSet == error);
31183118}
31193119 {#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#}
31213164 {#header_open|Inferred Error Sets#}
31223165 <p>
31233166 Because many functions in Zig return a possible error, Zig supports inferring the error set.
Original file line number Diff line number Diff line change @@ -31,6 +31,7 @@ comptime {
3131 _ = @import ("cases/incomplete_struct_param_tld.zig" );
3232 _ = @import ("cases/ir_block_deps.zig" );
3333 _ = @import ("cases/math.zig" );
34+ _ = @import ("cases/merge_error_sets.zig" );
3435 _ = @import ("cases/misc.zig" );
3536 _ = @import ("cases/namespace_depends_on_compile_var/index.zig" );
3637 _ = @import ("cases/new_stack_call.zig" );
Original file line number Diff line number Diff line change 1+ const A = error {
2+ PathNotFound ,
3+ NotDir ,
4+ };
5+ const B = error {OutOfMemory };
6+
7+ const C = A || B ;
8+
9+ fn foo () C ! void {
10+ return error .NotDir ;
11+ }
12+
13+ test "merge error sets" {
14+ if (foo ()) {
15+ @panic ("unexpected" );
16+ } else | err | switch (err ) {
17+ error .OutOfMemory = > @panic ("unexpected" ),
18+ error .PathNotFound = > @panic ("unexpected" ),
19+ error .NotDir = > {},
20+ }
21+ }
You can’t perform that action at this time.
0 commit comments