Functional update in Zig?

If I have a struct, and I want a copy with just a single field updated, is there some function in std I can use for that, or is it “do it yourself”?

const Point = struct { x: u32, y: u32 }

fn main() {
    const p = Point{ .x = 9, .y = 2 };
    const q = magic(p, .{ .x = 6 });
    assert(q.x == 6 and q.y = 2);
}

(In case this is an XY: I am writing a bunch of table-driven tests, and I want to quickly get values which are equal to a prototype while except for a few fields which differ).

pub fn update(base: anytype, diff: anytype) @TypeOf(base) {
    assert(builtin.is_test);
    var updated = base;
    inline for (std.meta.fields(@TypeOf(diff))) |f| {
        @field(updated, f.name) = @field(diff, f.name);
    }
    return updated;
}
9 Likes