Is this an abuse of decl literals?

I have a Rect and a Bounds type, where the Rect is 2D and the Bounds is 3D, and I’ve came up on this…

if (Rect.intersectsRect(
    .{ .min = @splat(-1), .size = @splat(2) },
    .fromBoundsXY(.encompassPoints(&local_points)),
))
    try visible_instances.append(instance);

I have mixed feeling about this, where it looks pretty lisp-y, but also non-zig-like feeling. Zls doesn’t know what to do with it, so go-to-definition fails currently. Any opinions?

1 Like

now I am curious about the declaration of intersectsRect and your Rect

I like it actually. I think this makes the case for function-call decl literals better than this does:

const new_thing: NewThing = .init(blah, blah);

// Not a compelling difference from

const new_thing = NewThing.init(blah, blah);

Using it for fields and parameters actually streamlines code.

Yeah, I mean, if it has the blessing of the community where this feature won’t get reversed, it does really get my imagination going. To me, it makes for much nicer higher-level math interfaces. I’ve been using zmath so far but I might end up changing over to something like this:

const Vector2 = packed struct {
    x: f32,
    y: f32,

    const zero: @This() = .{ .x = 0, .y = 0 };
    const one: @This() = .{ .x = 1, .y = 1 };

    fn init(x: f32, y: f32) @This() {
        return .{ .x = x, .y = y };
    }

    fn toVector(self: @This()) @Vector(2, f32) {
        return @bitCast(self);
    }
    fn fromVector(vec: @Vector(2, f32)) @This() {
        return @bitCast(vec);
    }

    fn add(first: @This(), second: @This()) @This() {
        return fromVector(first.toVector() + second.toVector());
    }
    fn subtract(first: @This(), second: @This()) @This() {
        return fromVector(first.toVector() - second.toVector());
    }
};

const position: Vector2 = .init(123, 456);
const target: Vector2 = .init(789, 123);

// Easier to read in my opinion (especially after multi-line formatting)
const result: Vector2 = .add(position, .subtract(target, .one));

// Dot chaining works too, but has always bothered me for math interfaces
const result2: Vector2 = position.add(target.subtract(.one));

1 Like

It’s in here, excuse the mess, this is my hobby code swamp

i know code swamp.
@splat seems ok to me. fast en short.

1 Like