Can 3D array initializarion be simplified?

The following code works.

const initial_state: CubeState = [3][3][3]u8{      [3][3]u8{                                          
    [3]u8{ 1, 2, 3 },
    [3]u8{ 4, 5, 6 },                          
    [3]u8{ 7, 8, 9 },                        
 },
...
}

Can it be simplified in another way ?

Regards !

Hello, Zig’s compiler can infer the types, so instead of:

const arr: [3][3][3]u8 = [3][3][3]u8{
        [3][3]u8{
            [3]u8{ 1, 2, 3 },
            [3]u8{ 1, 2, 3 },
            [3]u8{ 1, 2, 3 },
        },
        [3][3]u8{
            [3]u8{ 1, 2, 3 },
            [3]u8{ 1, 2, 3 },
            [3]u8{ 1, 2, 3 },
        },
        [3][3]u8{
            [3]u8{ 1, 2, 3 },
            [3]u8{ 1, 2, 3 },
            [3]u8{ 1, 2, 3 },
        },
    };

You can write:

const arr: [3][3][3]u8 = .{
        .{
            .{ 1, 2, 3 },
            .{ 1, 2, 3 },
            .{ 1, 2, 3 },
        },
        .{
            .{ 1, 2, 3 },
            .{ 1, 2, 3 },
            .{ 1, 2, 3 },
        },
        .{
            .{ 1, 2, 3 },
            .{ 1, 2, 3 },
            .{ 1, 2, 3 },
        },
    };
4 Likes

https://ziglang.org/download/0.14.0/release-notes.html#splat-Supports-Arrays

With newest Zig, you can also use the @splat builtin to initialize your array(s) with the same value (if this applies in your case, and you do not need different values when initializing your data).

5 Likes

You can also decide to flatten your array. for example you could have an array of 27 u8, and index using z * ylen + ylen * xlen + x it would probably simplifies a lot of things. and it would probably me more convenient to use. You can even go further, decide to represent it as a packed struct backed by a u256, and this way you get the ability to use the == operator.

2 Likes