Delayed const variable initialization

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 13 07:41:35 PDT 2015


On 7/13/15 3:11 AM, Yuxuan Shui wrote:
> How can I do something like this?
>
> const(A) x;
> if (condition) {
>    x = func1();
> } else {
>    x = func2();
> }
>
> This is a valid use case, and to make this work I'll have to use
> Rebindable, which is really inconvenient.


auto xvalue() {
   if(condition) {
      return func1();
   } else {
      return func2();
   }
}
const(A) x = xvalue();

Essentially you can assign on initialization, so you have to encapsulate 
the initialization into one call. D allows nested functions quite 
easily, so you can do this.

You can also do a temporary lambda that you call immediately, but I'm 
not 100% sure of the syntax. Someone will chime in with the answer :)

-Steve


More information about the Digitalmars-d-learn mailing list