How to initialise a large struct of 2D Vectors with default values

Hi all,

I’m currently porting a old C implementation of asteroids into Zig for a way to get more practice using Zig. Currently, for the player I’ve defined the struct below, and I now need to extend the number of rows from 3 to 9 to represent an asteroid. I could just copy and paste the extra rows, but is there a more elegant way to so this? I’d ask an AI, but they do tend to just make stuff up. Cheers.

var world_vert = [P_VERTS]Vector2d{
    Vector2d{ .x = 0.0, .y = 0.0 },
    Vector2d{ .x = 0.0, .y = 0.0 },
    Vector2d{ .x = 0.0, .y = 0.0 },
};

You can use the ** operator

https://ziglang.org/documentation/master/#Arrays

var world_vert = [_]Vector2d{.{ .x = 0.0, .y = 0.0 }} ** P_VERTS;

This defines an array (in this case of length 1) which is then repeated P_VERTS times.

Notice, that you also don’t need to repeat the Vector2d type annotation, it is inferred

4 Likes

Two other options are:

const world_vert: [P_VERTS]Vector2D = @splat(.{ .x = 0, .y = 0 });

…or if the whole array is just zeroes anyway:

const world_vert = std.mem.zeroes([P_VERTS]Vector2D);
4 Likes