On branch main
modified: src/ch08.md new file: src/ex-ch08-01.zig
This commit is contained in:
34
src/ch08.md
34
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");
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
28
src/ex-ch08-01.zig
Normal file
28
src/ex-ch08-01.zig
Normal file
@@ -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");
|
||||
}
|
||||
Reference in New Issue
Block a user