Skip to content

Commit 6e9fbb1

Browse files
authored
[spec/arrays] Improve slicing docs (#3645)
Mention start and end indexes. Expand example, show .ptr, show slicing a slice. Change Identifier[] to Expression[].
1 parent 307cf03 commit 6e9fbb1

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

spec/arrays.dd

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -229,28 +229,38 @@ assert(*p == 2);
229229

230230
$(P See $(DDSUBLINK spec/expression, pointer_arithmetic, *AddExpression*) for details.)
231231

232+
232233
$(H2 $(LNAME2 slicing, Slicing))
233234

234235
$(P $(I Slicing) an array means to specify a subarray of it.
236+
This is done by supplying two index expressions.
237+
The elements from the start index up until the end index are selected.
238+
Any item at the end index is not included.
239+
)
240+
$(P
235241
An array slice does not copy the data, it is only another
236242
reference to it. Slicing produces a dynamic array.
237-
For example:
238243
)
239244

240245
$(SPEC_RUNNABLE_EXAMPLE_RUN
241246
---------
242-
int[10] a; // declare array of 10 ints
247+
int[3] a = [4, 5, 6]; // static array of 3 ints
243248
int[] b;
244249

245-
b = a[1..3]; // a[1..3] is a 2 element array consisting of
250+
b = a[1..3]; // a[1..3] is a 2 element dynamic array consisting of
246251
// a[1] and a[2]
247-
assert(b[1] == 0);
252+
assert(b == [5, 6]);
253+
assert(b.ptr == a.ptr + 1);
254+
248255
a[2] = 3;
249-
assert(b[1] == 3);
256+
assert(b == [5, 3]);
257+
258+
b = b[1..2];
259+
assert(b == [3]);
250260
---------
251261
)
252262

253-
$(P $(I Identifier)[] is shorthand for a slice of the entire array.
263+
$(P $(I Expression)`[]` is shorthand for a slice of the entire array.
254264
)
255265

256266
$(P Slicing

0 commit comments

Comments
 (0)