Created
October 18, 2021 14:26
-
-
Save thomas-mangin/c55ca8be94cddbcb9b6423e442ee6258 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Another suggestion from watching | |
// https://www.youtube.com/watch?v=AHc4x1uXBQE&t=336s | |
// with my (genuine) 1 hour zig coding experience, I naively believe | |
// that this sould remove the memory issue within the union. | |
// and therefore is a slight improvement on the presented enum solution | |
const std = @import("std"); | |
const stdout = std.io.getStdOut().writer(); | |
const Button = struct { | |
fn draw(self: @This()) !void { | |
try stdout.print("button.draw: I draw a {s}.\n", .{self}); | |
} | |
pub fn format( | |
self: @This(), | |
comptime fmt: []const u8, | |
options: std.fmt.FormatOptions, | |
writer: anytype, | |
) !void { | |
_ = fmt; | |
_ = options; | |
try writer.print("button", .{}); | |
} | |
}; | |
const Slider = struct { | |
fn draw(self: @This()) !void { | |
try stdout.print("slider.draw: I draw a {s}.\n", .{self}); | |
} | |
pub fn format( | |
self: @This(), | |
comptime fmt: []const u8, | |
options: std.fmt.FormatOptions, | |
writer: anytype, | |
) !void { | |
_ = fmt; | |
_ = options; | |
try writer.print("slider", .{}); | |
} | |
}; | |
const widgetTag = enum { | |
button, | |
slider, | |
}; | |
const Widget = union(widgetTag) { | |
button: *Button, | |
slider: *Slider, | |
fn draw(self: @This()) !void { | |
switch (self) { | |
.button => try self.button.draw(), | |
.slider => try self.slider.draw(), | |
} | |
} | |
}; | |
pub fn main() !void { | |
var b = Button{}; | |
var s = Slider{}; | |
var widget = Widget{ .button = &b }; | |
try stdout.print("type {s}\n", .{@TypeOf(widget)}); | |
try widget.draw(); | |
widget = Widget{ .slider = &s }; | |
try widget.draw(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment