diff --git a/day02-hard/src/main.zig b/day02-hard/src/main.zig index 7e4eca3..a0bfa56 100644 --- a/day02-hard/src/main.zig +++ b/day02-hard/src/main.zig @@ -1,5 +1,14 @@ const std = @import("std"); +fn setMaxValue(field: anytype, new_value: anytype) void { + comptime { + if (!std.meta.trait.isPtrTo(@typeInfo(@TypeOf(new_value)))(@TypeOf(field))) { + @compileError("Expects field to be pointer type to new_value."); + } + } + field.* = @max(field.*, new_value); +} + const Cubes = struct { red: u32 = 0, green: u32 = 0, @@ -10,21 +19,15 @@ const Cubes = struct { } fn setRed(self: *Cubes, value: u32) void { - if (self.red < value) { - self.red = value; - } + setMaxValue(&self.red, value); } fn setGreen(self: *Cubes, value: u32) void { - if (self.green < value) { - self.green = value; - } + setMaxValue(&self.green, value); } fn setBlue(self: *Cubes, value: u32) void { - if (self.blue < value) { - self.blue = value; - } + setMaxValue(&self.blue, value); } };