ragnar
ragnar

Reputation: 388

Does Zig support the union of anonymous structs and arrays?

Is this possible in zig? And if so how would something like the following C++ code look in Zig?

template<class T>
class vec3
{
    union
    {
        struct{ T x,y,z; };
        T vec_array[3];
    };
};

Upvotes: 0

Views: 1356

Answers (1)

InKryption
InKryption

Reputation: 175

No, there is no such thing supported in Zig, and it is unlikely there ever will be. The closest you'll get is something like this:

const std = @import("std");

pub fn Vec3(comptime T: type) type {
    return extern union {
        xyz: extern struct { x: T, y: T, z: T },
        arr: [3]T,
    };
}

test {
    var v3: Vec3(u32) = .{ .arr = .{ 42, 73, 95 } };
    try std.testing.expectEqual(v3.arr[0], v3.xyz.x);
    try std.testing.expectEqual(v3.arr[1], v3.xyz.y);
    try std.testing.expectEqual(v3.arr[2], v3.xyz.z);
}

where the extern qualifiers here make the containers behave in accordance with the C ABI (and in the case of the union, makes it defined behavior to access any member).

See this comment under proposal #985 for a fairly comprehensive rationale on as to why "anonymous field nesting" was rejected.

Upvotes: 1

Related Questions