Why does this fail?

    struct F
    {
        int i;
        ushort _x;
        void x(ushort v) pure
        {_x = v;}
        ushort x() const
        { return _x; }
    }

    immutable F f1 = () pure {
    F lf = F();
    return lf; }();
// Error: cannot implicitly convert expression delegate () => lf() of type F to immutable(F)

    F makeF() pure
    {
        F lf = F();
        return lf;
    }
    immutable F f2 = makeF();
// Error: cannot implicitly convert expression makeF() of type F to immutable(F)

Removing the methods in struct F compiles fine.

Background: I have a mixin(bitfields!(...)) in the struct which utilizes member functions.


/////////////
Idea:
Just found out that it works when making the struct static. But why does that help?

Is it because the compiler wouldn't be able to check whether methods in the struct are accessing non-immutable data in the enclosing context?
That would not make much sense though because the following works:

// Compiles fine!
int modi = 3;
void main ()
{
    static struct F
    {
int var() immutable { return modi; } // accessing modi from module scope
    }
    immutable f = () pure { F f = F(); return f; }();
}

So my explanation wouldn't make sense, since why would it be okay to use module-scope data and not enclosing context data?

So where does that limitation come from that I implicitly convert a nested struct to immutable in a pure function?


Reply via email to