...

/

Immutability of the Slice Versus the Elements

Immutability of the Slice Versus the Elements

This lesson explains immutability of the slice versus the elements and use of immutability in general.

We have seen earlier in this chapter that the type of an immutable slice has been printed as immutable(int[]). As the parentheses after immutable indicate, it is the entire slice that is immutable. Such a slice cannot be modified in any way; elements may not be added or removed, their values may not be modified and the slice may not be changed to provide access to a different set of elements:

Press + to interact
import std.stdio;
void main() {
immutable int[] immSlice = [ 1, 2 ];
immSlice ~= 3; // ← compilation ERROR
immSlice[0] = 3; // ← compilation ERROR
immSlice.length = 1; // ← compilation ERROR
immutable int[] immOtherSlice = [ 10, 11 ];
immSlice = immOtherSlice; // ← compilation ERROR
}

Taking immutability to that extreme may not be suitable in every case. In most cases, what is important is the immutability of the elements themselves. Since a slice is just a tool to access the elements, it should not matter if we make changes to the slice itself as long as the elements are not modified. This is especially true in the cases we have seen so far where the function receives a copy of the slice itself.

To specify that only the ...

Access this course and 1400+ top-rated courses and projects.