...
/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 elements are immutable, we use the immutable
keyword with parentheses that enclose just the element type. The code can be modified to make only the elements immutable
and not the slice itself.
import std.stdio;void main() {immutable(int)[] immSlice = [ 1, 2 ];immSlice ~= 3; // can add elementsimmSlice[0] = 3; // ← compilation ERRORimmSlice.length = 1; // can drop elementsimmutable int[] immOtherSlice = [ 10, 11 ];immSlice = immOtherSlice; /* can provide access to other elements */}
Although both the codes have similar looking syntax, they have different meanings.
import std.stdio;void main() {immutable int[] a = [1]; /* Neither the elements nor the * slice can be modified */immutable(int[]) b = [1]; /* The same meaning as above */immutable(int)[] c = [1]; /* The elements cannot be modified but the slice can be */}
This distinction has been in effect in some of the programs that we have written so far. As you may ...