Type Qualifiers

16.1 const and immutable

Can't modify through this reference. The data may change through other references.

Data never changes, anywhere. Implicitly shareable between threads.

mutable (default) Qualifiers are transitive: const on a struct makes everything reachable through it const.

string = immutable(char)[], so strings are safe to share and slice without copying.

int x = 5;
const(int)* cp = &x;          // pointer to const int
immutable int y = 10;
immutable(int)[] arr = [1, 2, 3];   // elements immutable, slice reassignable
const int[] carr = [1, 2];          // fully const (transitive)

void print(const(int)[] data) {}    // accepts mutable, const, or immutable arrays

16.2 inout (Qualifier Polymorphism)

inout(int)[] firstHalf(inout(int)[] arr) { return arr[0 .. $ / 2]; }
// returns mutable/const/immutable to match the argument

16.3 shared and __gshared

shared: data accessible from multiple threads. The type system restricts unsynchronized access (see Module 37).

__gshared: C-style global without type-system protection (unsafe, for interop).

Module-level and static variables are thread-local by default.

16.4 Implicit Conversions with Qualifiers

mutable → const ✓, immutable → const ✓, mutable ↔ immutable ✗ (except for unique results from pure functions, or via assumeUnique / .idup).