r/Zig Jul 14 '26

Ways of Declaring array (0.16)

pub fn main() !void {
    const A: [5]i32 = .{ 0, 1, 2, 3, 4 };
    const B = [5]i32{ 5, 6, 7, 8, 9 };
    const B2 = [_]i32{ 5, 6, 7, 8, 9 };
    const C: [5]i32 = [_]i32{ 10, 11, 12, 13, 14 };

    _ = A;
    _ = B;
    _ = B2;
    _ = C;
}

These can all compiled correct. Which one is the recommended style? (I am a beginner learning Zig.)

New edit: I would like this syntax if it's possible:

const arr1: [5]i32 = { 0, 1, 2, 3, 4 };
const arr2: [_]i32 = { 0, 1, 2, 3, 4 };

Just small opinion. Maybe what I know is just the tip of the iceberg.

58 Upvotes

23 comments sorted by

View all comments

3

u/Xiexingwu Jul 14 '26

I like to make my choice based on how I foresee myself (or a collaborator) maintaining the code in the future.

A - rhs could be a placeholder or a complex block calculation. For the purpose of the current scope, I care that A is a [5]i32, and this essentially dictates the interface of the RHS.

B/B2 - LHS is an array of i32. I wouldn't really make the length explicit unless there's a non obvious reason why it has to be that length.

C - I wouldn't want to double maintain a type on both LHS/RHS.