Calls to struct methods and immutable

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Thu Nov 15 05:53:53 PST 2012


The following code refuses to compile:

///////////////////////////////////////////////////////
import std.math;

struct Foo
{
       int a;
       int b;

       this(int a, int b)
       {
             this.a = a;
             this.b = b;
       }

       void check()
       {
             real c = (a ^^ 2 + b ^^ 2) ^^ 0.5;
             assert(c < 10);
       }
}


void main()
{
       auto foo = cast(immutable) Foo(3, 4);
       foo.check();
}
///////////////////////////////////////////////////////

... producing an error message: immustruct.d(25): Error: function 
immustruct.Foo.check () is not callable using argument types () immutable

The reason seems pretty evident -- making the instance immutable means that the 
temporary internal variable c in check() can't be (over)written.  At the same 
time, this feels a bit daft -- you're talking about a transient value that is 
never seen outside the function scope.

Is there any way of getting round this constraint so such temporary, transient 
variables are still permitted within methods of an immutable instance?

As a workaround, if I write a function external to Foo, e.g.

void check2(Foo foo)
{
       real c = (foo.a ^^ 2 + foo.b ^^ 2) ^^ 0.5;
       assert(c < 10);
}

... then calling foo.check2() runs without problem.  I'm just curious as to 
whether it can be done within a struct method too.


More information about the Digitalmars-d-learn mailing list