diff --git a/src/ch08.md b/src/ch08.md index e407e4c..d320c99 100644 --- a/src/ch08.md +++ b/src/ch08.md @@ -357,3 +357,37 @@ ptr_info.Pointer.child.writeAll(self, data); ## Использование маркированных объединений +... + +Вот рабочий полноценный пример: + +```zig +const std = @import("std"); +const os = std.os; + +const Writer = union(enum) { + file: File, + + fn writeAll(self: Writer, data: []const u8) !void { + switch (self) { + .file => |file| return file.writeAll(data), + } + } +}; + +const File = struct { + fd: os.fd_t, + + fn writeAll(self: File, data: []const u8) !void { + _ = try std.os.write(self.fd, data); + } +}; + + +pub fn main() !void { + const file = File{.fd = std.io.getStdOut().handle}; + const writer = Writer{.file = file}; + try writer.writeAll("hi\n"); +} + +``` diff --git a/src/ex-ch08-01.zig b/src/ex-ch08-01.zig new file mode 100644 index 0000000..9f55ec6 --- /dev/null +++ b/src/ex-ch08-01.zig @@ -0,0 +1,28 @@ + +const std = @import("std"); +const os = std.os; + +const Writer = union(enum) { + file: File, + + fn writeAll(self: Writer, data: []const u8) !void { + switch (self) { + .file => |file| return file.writeAll(data), + } + } +}; + +const File = struct { + fd: os.fd_t, + + fn writeAll(self: File, data: []const u8) !void { + _ = try std.os.write(self.fd, data); + } +}; + + +pub fn main() !void { + const file = File{.fd = std.io.getStdOut().handle}; + const writer = Writer{.file = file}; + try writer.writeAll("hi\n"); +}