Why am I getting the "error: unable to infer array size" in this simple example?

I’m trying to initialize an array of structs where the size is inferred automatically:

const std = @import("std");

test "indexing" {
    const cases: [_]struct { at: u8, input: []const u8, expect: u8 } = .{ .{
        .at = 0,
        .input = "foo",
        .expect = 'f',
    }, .{
        .at = 1,
        .input = "foo",
        .expect = 'o',
    }, .{
        .at = 2,
        .input = "foo",
        .expect = 'o',
    } };

    for (cases) |c| {
        try std.testing.expectEqual(c.expect, c.input[c.at]);
    }
}

However:

$ zig test test.zig
src/test.zig:5:19: error: unable to infer array size
    const cases: [_]struct { at: u8, input: []const u8, expect: u8 } = .{ .{
                  ^

I think we may all agree that the size can be inferred at compile time. Do I do something wrong?

I also tried to use a slice instead: const cases: []struct { .. } = &.{ .. } but to be honest I don’t know how to convert arrays to slices when a const/var is first initialized.

Zig can only infer array sizes in the initializer syntax. This should work:

const cases = [_]T {a, b, c};
3 Likes

Thank you! It works.