Type qualifiers modify a type by applying aTypeCtor.TypeCtors are:const,immutable,shared, andinout. Each applies transitively to all subtypes.
When examining a data structure or interface, it is very helpful to be able to easily tell which data can be expected to not change, which data might change, and who may change that data. This is done with the aid of the language typing system. Data can be marked as const or immutable, with the default being changeable (ormutable).
immutable applies to data that cannot change. Immutable data values, once constructed, remain the same for the duration of the program's execution. Immutable data can be placed in ROM (Read Only Memory) or in memory pages marked by the hardware as read only. Since immutable data does not change, it enables many opportunities for program optimization, and has applications in functional style programming.
const applies to data that cannot be changed by the const reference to that data. It may, however, be changed by another reference to that same data. Const finds applications in passing data through interfaces that promise not to modify them.
Both immutable and const aretransitive, which means that any data reachable through an immutable reference is also immutable, and likewise for const.
The simplest immutable declarations use it as a storage class. It can be used to declare a variable whose value never changes.
immutableint x = 3;// x is set to 3//x = 4; // error, x is immutable// x is initialized by a compile-time constant,// and it doesn't change, so the compiler knows its valuestaticassert(x == 3);char[x] s;staticassert(s.length == 3);
The type can be inferred from the initializer:
immutable y = 4;// y is of type inty = 5;// error, y is immutable
If the initializer is not present, the immutable variable can be initialized from the corresponding shared static constructor:
immutableint z;void main(){assert(z == 3);//z = 4; // error, z is immutable}sharedstaticthis(){ z = 3;// ok, can initialize immutable variable that doesn't// have a static initializer}
The initializer for a non-local/static immutable declaration must be evaluatable at compile time:
immutable x = 3 * 4;staticassert(x == 12);int foo(int f) {return f * 3; }int i = 5;//immutable y = i + 1; // error, cannot evaluate `i` at compile timeimmutable z = foo(2) + 1;// ok, foo(2) can be evaluated at compile timestaticassert(z == 7);
The initializer for a non-static local immutable declaration is evaluated at run time:
int foo(int f){immutable x = f + 1;// evaluated at run time x = 3;// error, x is immutable}
Because immutable is transitive, data referred to by an immutable variable is also immutable:
immutablechar[] s ="foo";s[0] = 'a';// error, s refers to immutable datas ="bar";// error, s is immutable
Immutable declarations can appear as lvalues, i.e. they can have their address taken, and occupy storage.
See also:Manifest Constants.
A const declaration is exactly like an immutable declaration, with the following differences:
Data that will never change its value can be typed as immutable. The immutable keyword can be used as atype qualifier:
immutable(char)[] s ="hello";
The immutable applies to the type within the following parentheses. So, whiles can be assigned new values, the contents ofs[] cannot be:
s[0] = 'b';// error, s[] is immutables =null;// ok, s itself is not immutable
Immutability is transitive, meaning it applies to anything that can be referenced from the immutable type:
immutable(char*)** p = ...;p = ...;// ok, p is not immutable*p = ...;// ok, *p is not immutable**p = ...;// error, **p is immutable***p = ...;// error, ***p is immutable
Immutable used as a storage class is equivalent to using immutable as a type qualifier for the entire type of a declaration:
immutableint x = 3;// x is typed as immutable(int)immutable(int) y = 3;// y is immutable
The first way is to use a literal that is already immutable, such as string literals. String literals are always immutable.
auto s ="hello";// s is immutable(char)[5]char[] p ="world";// error, cannot implicitly convert immutable// to mutable
The second way is to cast data to immutable. When doing so, it is up to the programmer to ensure that any mutable references to the same data are not used to modify the data after the cast.
char[] s = ['a'];s[0] = 'b';// okimmutable(char)[] p =cast(immutable)s;// ok, if data is not mutated// through s anymores[0] = 'c';// undefined behaviorimmutable(char)[] q =cast(immutable)s.dup;// always ok, unique referencechar[][] s2 = [['a', 'b'], ['c', 'd']];immutable(char[][]) p2 =cast(immutable)s2.dup;// dangerous, only the first// level of elements is uniques2[0] = ['x', 'y'];// ok, doesn't affect p2s2[1][0] = 'z';// undefined behaviorimmutable(char[][]) q2 = [s2[0].dup, s2[1].dup];// always ok, unique references
The.idup property is a convenient way to create an immutable copy of an array:
auto p = s.idup;p[0] = ...;// error, p[] is immutable
An immutable or const type qualifier can be removed with a cast:
immutableint* p = ...;int* q =cast(int*)p;
This does not mean, however, that one can change the data:
*q = 3;// allowed by compiler, but result is undefined behaviorThe ability to cast away immutable-correctness is necessary in some cases where the static typing is incorrect and not fixable, such as when referencing code in a library one cannot change. Casting is, as always, a blunt and effective instrument, and when using it to cast away immutable-correctness, one must assume the responsibility to ensure the immutability of the data, as the compiler will no longer be able to statically do so.
void f(constint* a);void main(){int x = 1; f(&x);assert(x == 1);// guaranteed to hold}
Immutable member functions are guaranteed that the object and anything referred to by thethis reference is immutable. They are declared as:
struct S{int x;void foo()immutable { x = 4;// error, `x` is immutablethis = S();// error, `this` is immutable }}
Note that usingimmutable on the left hand side of a method does not apply to the return type:
struct S{immutableint[] bar()// bar is still immutable, return type is not! { }}
To make the return typeimmutable, surround it with parentheses:
struct S{immutable(int[]) bar()// bar is now mutable, return type is immutable. { }}
To make both the return type and the methodimmutable, write:
struct S{immutable(int[]) bar()immutable { }}
See also: Nested Functions with Method Attributes.
Const types are like immutable types, except that const forms a read-onlyview of data. Other aliases to that same data may change it at any time.
Const member functions are functions that are not allowed to change any part of the object through the member function'sthis reference.
Functions that differ only in whether the parameters are mutable,const orimmutable, and have corresponding mutable,const orimmutable return types, can be combined into one function using theinout type constructor. Consider the following overload set:
int[] slice(int[] a,int x,int y) {return a[x .. y]; }const(int)[] slice(const(int)[] a,int x,int y) {return a[x .. y]; }immutable(int)[] slice(immutable(int)[] a,int x,int y) {return a[x .. y]; }
The code generated by each of these functions is identical. Theinout type constructor can combine them into one function:
inout(int)[] slice(inout(int)[] a,int x,int y) {return a[x .. y]; }
Theinout keyword forms a wildcard that stands in for mutable,const,immutable,inout, orinout const. When calling the function, theinout state of the return type is changed to match that of the argument type passed to theinout parameter.
inout can also be used as a type constructor inside a function that has a parameter declared withinout. Theinout state of a type declared withinout is changed to match that of the argument type passed to theinout parameter:
inout(int)[] asymmetric(inout(int)[] input_data){inout(int)[] r = input_data;while (r.length > 1 && r[0] == r[$-1]) r = r[1..$-1];return r;}
Inout types can be implicitly converted toconst orinout const, but to nothing else. Other types cannot be implicitly converted toinout. Casting to or frominout is not allowed in@safe functions.
void f(inoutint* ptr){constint* p = ptr;int* q = ptr;// errorimmutableint* r = ptr;// error}
A set of arguments to a function withinout parameters is considered a match if anyinout argument types match exactly, or:
If such a match occurs,inout is considered the common qualifier of the matched qualifiers. If more than two parameters exist, the common qualifier calculation is recursively applied.
| mutable | const | immutable | inout | inout const | |
| mutable (= m) | m | c | c | c | c |
| const (= c) | c | c | c | c | c |
| immutable (= i) | c | c | i | wc | wc |
| inout (= w) | c | c | wc | w | wc |
| inout const (= wc) | c | c | wc | wc | wc |
Theinout in the return type is then rewritten to match theinout qualifiers:
int[] ma;const(int)[] ca;immutable(int)[] ia;inout(int)[] foo(inout(int)[] a) {return a; }void test1(){// inout matches to mutable, so inout(int)[] is// rewritten to int[]int[] x = foo(ma);// inout matches to const, so inout(int)[] is// rewritten to const(int)[]const(int)[] y = foo(ca);// inout matches to immutable, so inout(int)[] is// rewritten to immutable(int)[]immutable(int)[] z = foo(ia);}inout(const(int))[] bar(inout(int)[] a) {return a; }void test2(){// inout matches to mutable, so inout(const(int))[] is// rewritten to const(int)[]const(int)[] x = bar(ma);// inout matches to const, so inout(const(int))[] is// rewritten to const(int)[]const(int)[] y = bar(ca);// inout matches to immutable, so inout(int)[] is// rewritten to immutable(int)[]immutable(int)[] z = bar(ia);}
Note: Shared types cannot be matched withinout.
Mutable data that is meant to be shared among multiple threads should bedeclared with theshared qualifier. This prevents unsynchronizedreading and writing to the data, which would otherwise cause data races.Theshared type attribute is transitive (likeconst andimmutable).
sharedint x;shared(int)* p = &x;//int* q = p; // error, q is not shared
For basic data types, reading and writing can normally be done withatomic operations. Usecore.atomic for portability:
import core.atomic;sharedint x;void fun(){//x++; // error, use atomicOp instead x.atomicOp!"+="(1);}
Warning: An individual read or write operation on shareddata is not an error yet by default. To detect these, use the-preview=nosharedaccess compiler option. Normal initialization isallowed without an error.
import core.atomic;int y;sharedint x = y;// OK//x = 5; // write error with preview flagx.atomicStore(5);// OK//y = x; // read error with preview flagy = x.atomicLoad();// OKassert(y == 5);
When working with larger types, manual synchronizationcan be used. To do that,shared can be cast away for theduration while mutual exclusion has been established:
struct T;shared T* x;void fun(){synchronized { T* p =cast(T*)x;// operate on `*p` }}
An unshared reference can be cast to shared only if the source datawill not be accessed for the lifetime of the cast result.
class C {}@trustedshared(C) create(){auto c =new C;// work with c without it escapingreturncast(shared)c;// OK}
Global (or static) shared variables are stored in common storage whichis accessible across threads. Global mutable variables are stored inthread-local storage by default.
To declare global/static data to be implicitly shared acrossmultiple threads without any compiler checks, see__gshared.
More than one qualifier may apply to a type. The order of application isirrelevant, for example given an unqualified typeT,const shared T andshared const T are the same type. For that reason, this document depictsqualifier combinations without parentheses unless necessary and in alphabeticorder.
Applying a qualifier to a type that already has that qualifier is legal buthas no effect, e.g. given an unqualified typeT,shared(const shared T)yields the typeconst shared T.
alias SInt =sharedint;alias IInt =immutableint;staticassert(is(immutable(SInt) == IInt));staticassert(is(shared(IInt) == IInt));
AssumingT is an unqualified type, the graph below illustrates howqualifiers combine (combinations withimmutable are omitted). For each node,applying the qualifier labeling the edge leads to the resulting type.
Values that have no mutable indirections (including structs that don'tcontain any field with mutable indirections) can be implicitly converted acrossmutable,const,immutable,const shared,inout andinout shared.
References to qualified objects can be implicitly converted according to thefollowing rules:
In the graph above, any directed path is a legal implicit conversion. Noother qualifier combinations than the ones shown is valid. If a directed pathexists between two sets of qualifiers, the types thus qualified are calledqualifier-convertible. The same information is shown below in tabularformat:
| from/to | mutable | const | shared | inout | const shared | const inout | inout shared | const inout shared | immutable |
| mutable | ✔ | ✔ | |||||||
| const | ✔ | ||||||||
| shared | ✔ | ✔ | |||||||
| inout | ✔ | ✔ | ✔ | ||||||
| const shared | ✔ | ||||||||
| const inout | ✔ | ✔ | |||||||
| inout shared | ✔ | ✔ | ✔ | ||||||
| const inout shared | ✔ | ✔ | |||||||
| immutable | ✔ | ✔ | ✔ | ✔ | ✔ |
If an implicit conversion is disallowed by the table, anExpression may be implicitly converted as follows:
AUnique Expression is one for which there are no other references to the value of the expression and all expressions it transitively refers to are either also unique or are immutable. For example:
void main(){immutableint** p =newint*(null);// ok, uniqueint x;//immutable int** q = new int*(&x); // error, there may be other references to ximmutableint y;immutableint** r =newimmutable(int)*(&y);// ok, y is immutable}
See also:Pure Factory Functions.
Otherwise, aCastExpression can be used to force a conversion when an implicit version is disallowed, but this cannot be done in@safe code, and the correctness of it must be verified by the user.