Skip to content

Document []const T and [*]const T #288

@aryzing

Description

@aryzing

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions