zig.guide icon indicating copy to clipboard operation
zig.guide copied to clipboard

Document `[]const T` and `[*]const T`

Open aryzing opened this issue 1 year ago • 0 comments

Great guide! Was able to start writing snippets right away! The only feature I've had to research outside the guide is the meaning of []const T and [*]const T types.

It's briefly shown in the Slices and Sentinel Termination chapters, although not really explained.

As I understood it, using const in this way means that the slice or many-item pointer won't be used to modify the underlying data, although says nothing about

  • whether the underlying data is modifiable,
  • whether the slice/mip itself is a var or const.
pub fn main() !void {
    var array1: [5]u8 = [_]u8{ 1, 2, 3, 4, 5 };

    const slice1: []const u8 = &array1;
    var slice2: []const u8 = &array1;
    const mip1: [*]const u8 = &array1;
    var mip2: [*]const u8 = &array1;

    // ...and all the above work too if `array1` was `const`

    slice2 = &array1; // to avoid error: local variable is never mutated
    mip2 = &array1; // to avoid error: local variable is never mutated

    // to avoid unused variable error
    std.debug.print("{any}\n{any}\n{any}\n{any}\n", .{ slice1, slice2, mip1, mip2 });
}

It may also be worth explaining that more types, like strings, can coerce to []const T and therefore advisable to use this type over the non-const version when the data doesn't need to be modified.

aryzing avatar Jan 05 '25 17:01 aryzing