Hello Zig Community,
I just have a few questions when it comes to Zig's arrays and slices.
-
May someone please explain what this
&.{…}does? Is this taking a reference to an anonymous struct? When would I ever use this? -
I feel like there's two different syntaxes around how to declare a slice. For example:
var array = [5]i32{ 1, 2, 3, 4, 5 };
const slice = array[1..4];
slice is type of *[3]i32. Ok that's fine, but then if I do something like this:
var array = [5]i32{ 1, 2, 3, 4, 5 };
const slice: []i32 = array[1..4];
slice is now type of []i32. My question is, what's the different between *[3]i32 and []i32. Why does Zig have these different ways for declaring a slice?
- This question is very similar to question 2, but I wanted to break it up into its own question. How I read
*[3]i32isI have a pointer to an array of size 3 of type i32. Ok that makes sense, but going back to this example:
var array = [5]i32{ 1, 2, 3, 4, 5 };
const slice = array[1..4]; // We know that this is of type *[3]i32
print("{d}", .{slice[0]}); // Prints 2
slice[0] doesn't make sense to me. Coming from a C background, I would view *[3]i32 as a double pointer, so to me, this makes more sense print("{d}", .{slice.*[0]}); But clearly there is something that I am missing, may someone please explain why my thinking is incorrect?
- When trying to pass an array to a function, I have seen this:
fn foo(array: []i32) void {
print("{any}", .{array});
}
pub fn main() void {
var array = [5]i32{ 1, 2, 3, 4, 5 };
foo(&array);
}
I don't understand why &array is declared like that. To me, it reads like I am passing in a double pointer to the function foo. Why is this the case? Is it just the syntax of language?
- Instead of doing
&array, I have also seenarray[0..].array[0..]makes way more sense to me than&array. Isarray[0..]the same as&array? Why would I choose one over the other?
Thanks!
vibes