Search⌘ K
AI Features

Immutability of the Slice Versus the Elements

Explore the concept of immutability in D programming by learning the distinction between immutable slices and immutable elements. Understand when and how to apply const and immutable keywords, working with string aliases and copying arrays using .dup and .idup. This lesson helps you grasp safe coding practices in managing data mutability.

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:

D
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 ...