Skip to content

Commit 577f9fd

Browse files
YujiriVexu
authored andcommitted
doc/langref: clarify behavior of slicing with constant indexes
Fixes #11219.
1 parent 397e654 commit 577f9fd

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

doc/langref.html.in

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2929,9 +2929,15 @@ test "basic slices" {
29292929
// Both can be accessed with the `len` field.
29302930
var known_at_runtime_zero: usize = 0;
29312931
const slice = array[known_at_runtime_zero..array.len];
2932+
try expect(@TypeOf(slice) == []i32);
29322933
try expect(&slice[0] == &array[0]);
29332934
try expect(slice.len == array.len);
29342935

2936+
// If you slice with comptime-known start and end positions, the result is
2937+
// a pointer to an array, rather than a slice.
2938+
const array_ptr = array[0..array.len];
2939+
try expect(@TypeOf(array_ptr) == *[array.len]i32);
2940+
29352941
// Using the address-of operator on a slice gives a single-item pointer,
29362942
// while using the `ptr` field gives a many-item pointer.
29372943
try expect(@TypeOf(slice.ptr) == [*]i32);
@@ -2974,22 +2980,26 @@ test "using slices for strings" {
29742980
}
29752981

29762982
test "slice pointer" {
2983+
var a: []u8 = undefined;
2984+
try expect(@TypeOf(a) == []u8);
29772985
var array: [10]u8 = undefined;
29782986
const ptr = &array;
2987+
try expect(@TypeOf(ptr) == *[10]u8);
29792988

2980-
// You can use slicing syntax to convert a pointer into a slice:
2981-
const slice = ptr[0..5];
2989+
// A pointer to an array can be sliced just like an array:
2990+
var start: usize = 0;
2991+
var end: usize = 5;
2992+
const slice = ptr[start..end];
29822993
slice[2] = 3;
29832994
try expect(slice[2] == 3);
29842995
// The slice is mutable because we sliced a mutable pointer.
2985-
// Furthermore, it is actually a pointer to an array, since the start
2986-
// and end indexes were both comptime-known.
2987-
try expect(@TypeOf(slice) == *[5]u8);
2988-
2989-
// You can also slice a slice:
2990-
const slice2 = slice[2..3];
2991-
try expect(slice2.len == 1);
2992-
try expect(slice2[0] == 3);
2996+
try expect(@TypeOf(slice) == []u8);
2997+
2998+
// Again, slicing with constant indexes will produce another pointer to an array:
2999+
const ptr2 = slice[2..3];
3000+
try expect(ptr2.len == 1);
3001+
try expect(ptr2[0] == 3);
3002+
try expect(@TypeOf(ptr2) == *[1]u8);
29933003
}
29943004
{#code_end#}
29953005
{#see_also|Pointers|for|Arrays#}

0 commit comments

Comments
 (0)