d语言的const,immutable修饰符

参考自d程序设计语言---我的博客http://my.oschina.net/u/218155/blog?fromerr=SwOkb7Sw fllow me


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;






}


转载于:https://my.oschina.net/u/218155/blog/612561

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值