參考自d程序設計語言---個人博客http://my.oschina.net/u/218155/blog?fromerr=SwOkb7Sw fllow methis
import std.stdio; import std.conv; //const immutable share struct Point { int x,y; } class A{ int a,b; string name; int[] fun(){ return [1,2]; } int [] gun() immutable{ return [1,2]; } immutable int[] hun(){ return [1,2]; } immutable(int)[] iun() immutable{ return [1,2]; } this() immutable{ a = 1; b = 1; name = "immutable"; } void setA(int a){ this.a = a; } } struct S{ private int[] a; this(immutable(S)source){ a = to!(int[])(source.a); } this(S source) immutable{ a = to!(immutable(int[])) (source.a); } } void print(immutable(int[]) data){ writeln(data); } void printNew(const(int[]) data){ writeln(data); } //inout change inout(char)*strchr(inout(char)*input ,int c); unittest { immutable (int[]) mydata = [10,20]; print(mydata); printNew(mydata); printNew([1,2]); S aa; auto b = immutable(S) (aa); writeln(typeid(typeof(b.a))); auto c = S(b); writeln(typeid(typeof(c.a))); immutable(int) over = 1; //over++; auto bod = over; //bod++; immutable p = 1.25; auto stru_p = immutable(Point)(0,0); auto stru_p2 = stru_p; assert(is(typeof(stru_p2.x) == immutable(int))); alias immutable (int[]) T1; alias immutable (int)[] T2; T1 t1_a = [1,2,3]; //t1_a[1] = 10; //t1_a = [4,5,6]; T2 t2_a = [1,2,3]; t2_a = [4,5,6]; //t2_a[0] = 999; //can't modify immutable data auto objA = new immutable(A); //auto objB = new A();//error assert(objA.a == 1); //objA.setA(11); //error can't modify //objA.a = 11;//error //immutable change int to other int changeA = 1; immutable(int) changeB = changeA; assert(changeB == 1); int changeC = changeB; int[] arrA = [1]; //immutable (int[]) arrB = arrA; }