I’m having some issues with zig arrays. I thought they were supposed to be similar to a scalar type in handling and not degrade to pointers like C (ie, when I call a function with an array argument, the whole array is passed by value, and it does’t turn into a pointer). Iit sometimes acts as a scalar – when you take the address you get a single item pointer – but sometimes act as a multivalues type since it is indexable. It’s a Shrodinger type - depending on how you interact with it you get different properties.
But I can’t seem to convert an array literal into a slice. How do I get array a
into const and a non-const slices?
(1) Why is this not allowed? const before the a
say’s I won’t reassign it. I understand this to some extent since arrays are supposed to be like screadonlyalars, but the type of the items is not u32
but is const u32
. They are stored in the rodata section binary, and no matter what I do, they will always be immutable. How do I carry that information around?
(2) This b
isn’t the same type as a
. Binding a
doesn’t contain mutable data, But b
seems to say it does. And b
is never modified, so is var/const different for arrays? Depending on what comes after this I need to ikeep changing this from var to const even though none of the code ever mutates the values, just the compiler can’t seem to prove it to itself.
(3) For a scalar this would make a binary copy, and I believe it would do the same for a @Vector
, but this doesn’t seem to work for arrays.
(4) I thought b[0..]
would return a slice of all of b. There does this pointer come from?
// (1) const a: [3]const u32 = [_]u32{ 3, 1, 4 }; // pointer modifier const not allowed on array child type
const a = [_]u32{ 3, 1, 4 };
// (2) var b: [3]u32 = a;
const b: [3]u32 = a; // (3)
const t: []u32 = b[0..]; // (4) expected []u32, found *const [3]u32
I can’t figure how to slices (mutable and immutable) of an array literal. It keeps winding up as a pointer to an array.
Side note: Is there a way to cast a [3]u32
to a [2]u32
easily like how @intCast
cn be used to cast from a u64 to a u32?