initializing immutable structs

bearophile bearophileHUGS at lycos.com
Fri Mar 26 05:30:39 PDT 2010


Paul D. Anderson:
> The primary difficulty is that I can't use a static initializer but need to use a constructor instead. But the constructor isn't allowed as it's non-constant expression. How do I declare the struct variable and initialize it separately?
> 
> The second difficulty is that when I declare it immutable I get a "can't implicitly convert an expression of type X to to immutable X" error. I tried an explicit cast and that didn't work.

Do not use casts, forget they exist. In safe mode you can't use them.
Show us the code that doesn't work as you want, because I have no ESP powers.

This shows how you can use immutable structs:

struct Foo {
    int x, y;
    this(int xx, int yy) {
        this.x = xx;
        this.y = yy;
    }
}

immutable struct Bar {
    int x, y;
    this(int xx, int yy) {
        this.x = xx;
        this.y = yy;
    }
}

struct Spam {
    int x, y;
    immutable this(int xx, int yy) { // ?
        this.x = xx;
        this.y = yy;
    }
}

void main() {
    immutable Foo f1 = Foo(1, 2);
    auto f2 = immutable(Foo)(1, 2);
    Foo f3 = Foo(1, 2);
    immutable Foo f4 = f3;
    auto b1 = Bar(1, 2);
    Bar b2 = Bar(1, 2);

    Spam s1 = Spam(1, 2);
    s1.x = 10;
}

But s1 is not immutable, I don't know what "immutable this()" means.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list