Would it make sense for “test_basic_slices.zig”, in the main doc, to reflect on…
test "slice evaluates to array address" {
var array = [_]u8{ 1,2,3,4,5 };
var slice = array[0..];
_ = &slice;
try expect(&array == slice);
try expect(&array == slice.ptr); // also
}
This seems implied, but not clarified, and perhaps there are some nuances that could be mentioned, too(?)
I’m not sure what you are asking about?
A slice is just a pointer and a length, you can think of it like this struct
const Slice = struct {
ptr: [*]T,
len: usize,
};
var slice: Slice = .{ .ptr = &array[0], .len = array.len };
T being the element type, and the pointer being const or not depending on mutability.
It’s just pointing to the first element and has a length.
ofc you can make a slice that starts in the middle or end of the array and with a shorter length than the remaining total length.
A caveat to be aware of: when you slice with from 0 with a comptime known length you will get a pointer to an array instead of a slice, you won’t notice most cases since pointers to an array can coerce to a slice.
Which is the case with your example, I point this out because you cannot == slices, but you can == pointers, if slice was actually a slice then you would need to compare to the ptr field.
Yes, you’ve got it. So, agreed: the documentation DOES state the caveat about comptime-known-length (that you’ll get a pointer to an array instead of a slice), and I guess that’s all there really is to it, here. But that led me to believe I wouldn’t be able to slice.ptr (since you can’t array.ptr, and that should be a pointer to an array, technically, since the length was comptime-known), but this code disproves that. Before that, though, I wasn’t sure if &array would == slice, though I hoped/expected that that’s exactly what I’d get in this case. Perhaps detail like this is unnecessary or duplicate, but I was unsure until I looked at the code and then ran this test to confirm.