Skip to content

Instantly share code, notes, and snippets.

@thomas-mangin
Created October 18, 2021 14:26
Show Gist options
  • Save thomas-mangin/c55ca8be94cddbcb9b6423e442ee6258 to your computer and use it in GitHub Desktop.
Save thomas-mangin/c55ca8be94cddbcb9b6423e442ee6258 to your computer and use it in GitHub Desktop.
// 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