#slices and pointers to arrays

1 messages · Page 1 of 1 (latest)

halcyon wraith
#

why the following code doesn't work?

const ns = [_]u8{ 12, 54, 12, 6 };
var ls: *const []u8 = ns[0..];

shouldnt return type of a slicing operation be a slice not a pointer to an array?

lofty blade
#

*const []u8 is not a slice or a pointer to array, it's a pointer to a slice. with var ls: []const u8 = ns[0..]; this code should work.

#

the result of a slicing operation is a pointer to an array when the length is comptime-known. but a pointer to an array can coerce to a slice, so in effect the result of slicing is always usable as a slice

#

pointer to array just has the benefit of a comptime-known length which is sometimes helpful

glacial locust
#

Probably worth reminding that a *const []T is very unlikely to be the type you want. Yeah, there may be uses, but []const u8 is almost always what you want. Similar to using a *std.mem.Allocator.

vagrant portal
#

also array[0..] is exactly equivalent to &array, and the latter is generally preferred