immutability - 如何创建对不可变类的可重新分配引用?

标签 immutability d

如何创建对不可变类的引用,同时保持重新分配引用的能力,有点像字符串

import std.stdio;

immutable class Test {
    string test(){
        return "test";
    }
}

void main(){
    auto test = new Test;
    writeln(test.test);
}

这会导致错误,因为创建的实例不是不可变的:

test.d(14): Error: immutable method test.Test.test is not callable using a mutable object

new immutable 也不起作用,因为之后无法为结果变量分配新的变量。

immutable(Test)* 可以,但是有没有办法避免指针?

最佳答案

使用 std.typecons.Rebindable http://dpldocs.info/experimental-docs/std.typecons.Rebindable.html#examples

import std.typecons;
class Widget { int x; int y() const { return x; } }
auto a = Rebindable!(const Widget)(new Widget);
// Fine
a.y();
// error! can't modify const a
// a.x = 5;
// Fine
a = new Widget;

关于immutability - 如何创建对不可变类的可重新分配引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44740624/

相关文章:

immutability - ClojureScript、Elm、PureScript、GHCJS 等不可变语言如何编译为可变 javascript?

binding - 在 D 中使用 Windows 库的正确方法?

d - 如何从 D JSON 类型中删除 JSON 对象键?

c# - .NET - System.Collections.Immutable 某处是否有单向链表?

c++ - c++中的持久化数据结构

javascript - 从多个源异步更新 React 状态

c# - 在非不可变类型中覆盖 == 运算符

visual-studio - 如何为 DUB 包生成 PDB 文件?

functional-programming - 返回 D 中函数的函数的纯函数

coding-style - 重函数调用嵌套的可读性?