extract setMaxValue

main
Inga 🏳‍🌈 12 months ago
parent e8378d440f
commit 0be3a8ae25
  1. 21
      day02-hard/src/main.zig

@ -1,5 +1,14 @@
const std = @import("std"); 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 { const Cubes = struct {
red: u32 = 0, red: u32 = 0,
green: u32 = 0, green: u32 = 0,
@ -10,21 +19,15 @@ const Cubes = struct {
} }
fn setRed(self: *Cubes, value: u32) void { fn setRed(self: *Cubes, value: u32) void {
if (self.red < value) { setMaxValue(&self.red, value);
self.red = value;
}
} }
fn setGreen(self: *Cubes, value: u32) void { fn setGreen(self: *Cubes, value: u32) void {
if (self.green < value) { setMaxValue(&self.green, value);
self.green = value;
}
} }
fn setBlue(self: *Cubes, value: u32) void { fn setBlue(self: *Cubes, value: u32) void {
if (self.blue < value) { setMaxValue(&self.blue, value);
self.blue = value;
}
} }
}; };

Loading…
Cancel
Save