Movatterモバイル変換


[0]ホーム

URL:


DLang LogoDLang Tour
Menu

Mutability

D is a statically typed language: once a variable has been declared,its type can't be changed from that point onwards. This allowsthe compiler to prevent bugs early and enforce restrictionsat compile time. Good type-safety provides the support one needsto make large programs safer and more maintainable.

There are several type qualifiers in D but the most commonly used ones areconst andimmutable.

immutable

In addition to a static type system, D provides type qualifiers (sometimes alsocalled "type constructors") that enforce additional constraints on certainobjects. For example animmutable object can only be initialized once andafter that isn't allowed to change.

immutable int err = 5;// or: immutable err = 5 and int is inferred.err = 5; // won't compile

immutable objects can thus be safely shared among different threads with nosynchronization, because they never change by definition. This also implies thatimmutable objects can be cached perfectly.

const

Objects can't be modified through a const reference.A mutable reference to the same object can still modify it.Aconst pointer can be created from either amutable orimmutable object. It is commonfor APIs to acceptconst arguments to ensure they don't modify the input asthat allows the same function to process both mutable and immutable data.

void foo(const char[] s){    // if not commented out, next line will    // result in error (can't modify const):    // s[0] = 'x';    import std.stdio : writeln;    writeln(s);}// thanks to `const`, both calls will compile:foo("abcd"); // string is an immutable arrayfoo("abcd".dup); // .dup returns a mutable copy

Transitivity

Bothimmutable andconst aretransitive type qualifiers, which ensures that onceconst is applied to a type, it applies recursively to every sub-component of that type.

immutable int* p = new int;p = null; // error*p = 5; // error

The element type of a pointer (or array) can be qualified separately:

immutable p = new int; // immutable(int*)immutable(int)* q = p; // OK, mutable pointerq = null; // OK*q = 5; // error

Thestring type is defined asimmutable(char)[]:

string s = "hi";s ~= " world"; // OK, append new characterss[0] = 'c'; // error, can't change existing data

In-depth

Basic references

Advanced references

rdmd playground.d


[8]ページ先頭

©2009-2025 Movatter.jp