ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.82k stars 2.55k forks source link

BoundedArray does not support array initialization syntax #21437

Closed buzmeg closed 1 month ago

buzmeg commented 1 month ago

Zig Version

0.14.0-dev.1410+13da34955

Steps to Reproduce and Observed Behavior

The following code fails with "example.zig:8:26: error: type 'bounded_array.BoundedArrayAligned(i32,4,4)' does not support array initialization syntax":

const std = @import("std");

pub fn main() !void {
    const someA = [4]i32;
    const someBA = std.BoundedArray(i32, 4);

    const a: someA = .{0, 1, 2, 3};
    const ba: someBA = .{0, 1, 2, 3};

    std.debug.print("SS: {any} {any}\n", .{a, ba});
}

Expected Behavior

Expect both declarations to work

mlugg commented 1 month ago

std.BoundedArray is a userspace type in the standard library; Zig does not permit such types to be inititalized with array initialization syntax. Use its fromSlice method instead:

const SomeBa = std.BoundedArray(i32, 4);

const ba: SomeBa = try .fromSlice(&.{ 0, 1, 2, 3 });
// equivalently
const ba = try SomeBa.fromSlice(&.{ 0, 1, 2, 3 });
buzmeg commented 1 month ago

That first form doesn't seem to work if in a struct but the second form does seem to work like so:

const std = @import("std");

pub fn main() !void {
    const BA = std.BoundedArray(i32, 4);

    const StructBA = struct {
        aa: i32,
        bb: BA,
    };

    const sba: [1]StructBA = .{
        .{
            .aa = 42,
            .bb = try BA.fromSlice(&.{0, 1, 2, 3}),
        },
    };

    std.debug.print("SS: {any}\n", .{sba, });
}

Thanks.

mlugg commented 1 month ago

That first form doesn't seem to work if in a struct

Replacing the relevant line with the following works fine for me:

            .bb = try .fromSlice(&.{ 0, 1, 2, 3 }),

You're on a slightly older Zig build, it's possible there was a bug with decl literals (the feature allowing this shorthand) in that version.