doc/langref: clarify behavior of slicing with constant indexes

Fixes #11219.
This commit is contained in:
Yujiri 2022-07-14 06:27:01 +00:00 committed by Veikka Tuominen
parent 397e6547a9
commit 577f9fdbae

View File

@ -2929,9 +2929,15 @@ test "basic slices" {
// Both can be accessed with the `len` field. // Both can be accessed with the `len` field.
var known_at_runtime_zero: usize = 0; var known_at_runtime_zero: usize = 0;
const slice = array[known_at_runtime_zero..array.len]; const slice = array[known_at_runtime_zero..array.len];
try expect(@TypeOf(slice) == []i32);
try expect(&slice[0] == &array[0]); try expect(&slice[0] == &array[0]);
try expect(slice.len == array.len); try expect(slice.len == array.len);
// If you slice with comptime-known start and end positions, the result is
// a pointer to an array, rather than a slice.
const array_ptr = array[0..array.len];
try expect(@TypeOf(array_ptr) == *[array.len]i32);
// Using the address-of operator on a slice gives a single-item pointer, // Using the address-of operator on a slice gives a single-item pointer,
// while using the `ptr` field gives a many-item pointer. // while using the `ptr` field gives a many-item pointer.
try expect(@TypeOf(slice.ptr) == [*]i32); try expect(@TypeOf(slice.ptr) == [*]i32);
@ -2974,22 +2980,26 @@ test "using slices for strings" {
} }
test "slice pointer" { test "slice pointer" {
var a: []u8 = undefined;
try expect(@TypeOf(a) == []u8);
var array: [10]u8 = undefined; var array: [10]u8 = undefined;
const ptr = &array; const ptr = &array;
try expect(@TypeOf(ptr) == *[10]u8);
// You can use slicing syntax to convert a pointer into a slice: // A pointer to an array can be sliced just like an array:
const slice = ptr[0..5]; var start: usize = 0;
var end: usize = 5;
const slice = ptr[start..end];
slice[2] = 3; slice[2] = 3;
try expect(slice[2] == 3); try expect(slice[2] == 3);
// The slice is mutable because we sliced a mutable pointer. // The slice is mutable because we sliced a mutable pointer.
// Furthermore, it is actually a pointer to an array, since the start try expect(@TypeOf(slice) == []u8);
// and end indexes were both comptime-known.
try expect(@TypeOf(slice) == *[5]u8);
// You can also slice a slice: // Again, slicing with constant indexes will produce another pointer to an array:
const slice2 = slice[2..3]; const ptr2 = slice[2..3];
try expect(slice2.len == 1); try expect(ptr2.len == 1);
try expect(slice2[0] == 3); try expect(ptr2[0] == 3);
try expect(@TypeOf(ptr2) == *[1]u8);
} }
{#code_end#} {#code_end#}
{#see_also|Pointers|for|Arrays#} {#see_also|Pointers|for|Arrays#}