authorgravatar for yujiri@disroot.orgYujiri <yujiri@disroot.org> 2022-07-14 06:27:01+00:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2022-07-15 10:17:22+03:00
log577f9fdbae12eabbbf87bd2cc36a1565df3153b2
tree6c7be145426bc3fc709b254850a96381dfe67571
parent397e6547a9b1745df520a65ca615934b8c0a02d2

doc/langref: clarify behavior of slicing with constant indexes

Fixes #11219.

1 files changed, 20 insertions(+), 10 deletions(-)

doc/langref.html.in+20-10
......@@ -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
29762982test "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#}