...
/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'll cover the following...
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:
import std.stdio;void main() {immutable int[] immSlice = [ 1, 2 ];immSlice ~= 3; // ← compilation ERRORimmSlice[0] = 3; // ← compilation ERRORimmSlice.length = 1; // ← compilation ERRORimmutable 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 ...