immutable / inout / pure headaches

Steven Schveighoffer schveiguy at yahoo.com
Fri Jul 6 14:28:39 UTC 2018


On 7/6/18 7:10 AM, Timoses wrote:
> I dared once again getting into immutable by adding an "immutable" 
> keyword which causes a chain of actions to be taken.
> I feel like I'm lost in a jungle of immutable, inout and pure (perhaps 
> more will join the party...).
> 
> To start off, why does this not work?
> 
> 
>      class Test
>      {
>          private S s;
>          this(S t) { this.s = t; }
>          this(immutable S t) immutable { this.s = t; }
> 
>          inout(Test) get() inout
>          {
>              // Error: none of the overloads of __ctor are callable 
> using a inout object, candidates are:
> //onlineapp.d(10):        onlineapp.Test.this(S t)
> //onlineapp.d(11):        onlineapp.Test.this(immutable(S) t)
>               return new inout Test(this.s);
>          }

inout is not a compile-time wildcard, it's a runtime one. So it doesn't 
know how to convert an immutable to an inout. Essentially, inside this 
function, the compiler has no idea whether the real thing is an 
immutable, const, mutable, etc.

The fix is simple, replace both your constructors with one inout 
constructor:

this(inout(S) t) inout { this.s = t; }

And it will work for everything.

One word of caution though -- inout is viral (just like immutable). 
Everything you use has to support it, or it breaks down.

-Steve


More information about the Digitalmars-d-learn mailing list