是否可以防止 D2 中变量的非传递性重新分配?
是否可以防止 D2 中变量的非传递性重新分配?
例如:
final int[] a = [0];
a[0] = 1; // OK.
a = []; // ERROR.
我在这里只看到 const
和 immutable
: http://www.dlang.org/const3.html
Is it possible to prevent reassignment of variables non-transitively in D2?
For example:
final int[] a = [0];
a[0] = 1; // OK.
a = []; // ERROR.
I only see const
and immutable
here:
http://www.dlang.org/const3.html
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不。你拥有的是 const 和 immutable,它们是可传递的(如果不是的话,它们真的无法工作)。你可以做,
但不是你想要的。
当 const 和 immutable 具有传递性时,编译器可以提供更好的保证。此外,
不可变
对于线程确实没有任何用处(其存在的主要原因之一),除非它是可传递的,并且因为任何不可变
都必须能够< code>const、const
也必须是传递的。因此,它们必然不能用于简单地防止变量重新分配。并且该语言中没有其他结构可以这样做。No. What you have is
const
andimmutable
, and they are transitive (they really wouldn't work if they weren't). You can doBut not what you're looking for.
The compiler can give better guarantees when
const
andimmutable
are transitive. Also,immutable
really isn't of any use for threading (one of its main reasons for existing) unless it's transitive, and because anything that'simmutable
must be able to beconst
,const
must be transitive as well. So, of necessity, they can't be used for simply protecting against variable reassignment. And there are no other constructs in the language for doing so.