Slices and Other Array Features
In this lesson, we will discuss slices and other array features like array.length, .dup etc.
We'll cover the following
We have seen earlier in this chapter how elements are grouped as a collection in an array. This lesson further elaborates on that concept by explaining the features of the arrays.
Before going any further, here are a few brief definitions of some terms that happen to be close in meaning:
-
Array: the general concept of a group of elements that are located side by side and are accessed by indexes
-
Fixed-length array (static array): an array with a fixed number of elements; this type of array owns its elements and doesn’t allow one to change the length of the array
-
Dynamic array: an array that can gain or lose elements; this type of array provides access to elements that are owned by the D runtime environment
-
Slice: another name for the dynamic array
When we use slice, it will mean a dynamic array. On the contrary, when we use the term array we mean either a slice or a fixed-length array with no distinction.
Slices #
Slices have the same feature as dynamic arrays. Slices are called dynamic arrays since we can change their length at runtime, and they are called slices for providing access to portions of other arrays. They allow using those portions as if they are separate arrays.
Slices are defined by a number range syntax that corresponds to the indexes that specify the beginning and the end of the range:
beginning_index .. one_beyond_the_end_index
In the number range syntax, the beginning index is a part of the range, but the end index is outside of the range:
/* ... */ = monthDays[0 .. 3]; // 0, 1, and 2 are included; but not 3
Note: Number ranges are different from Phobos ranges. Phobos ranges are about struct and class interfaces.
As an example, we can slice the monthDays array to be able to use its parts as four smaller sub-arrays:
int[12] monthDays =
[ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
int[] firstQuarter = monthDays[0 .. 3];
int[] secondQuarter = monthDays[3 .. 6];
int[] thirdQuarter = monthDays[6 .. 9];
int[] fourthQuarter = monthDays[9 .. 12];
The four variables in the code above are slices; they provide access to four parts of an already existing array. An important point worth stressing here is that those slices do not have their own elements. They merely provide access to the elements of the actual array. Modifying an element of a slice modifies the element of the actual array. To see this, let’s modify the first elements of each slice and then display the actual array:
Get hands-on with 1400+ tech skills courses.