Search code examples
arraysinitializationconst-correctnessd

How do you initialise an array of const values in D2?


Essentially, I want to be able to do something like this:

struct Foo
{
  const(int)[2] ints;

  this(int x, int y)
  {
    ints = [x, y];
  }
}

but this doesn't work. The compiler (DMD 2.048) just complains that ints isn't mutable.

How are you supposed to initialise the array?


Solution

  • One way is to implement constructor is this way:

      this(int x, int y) 
      {
        auto i2 = cast(int[2]*)&ints;
        *i2 = [x, y];
      }
    

    const is readonly view, so the constructor creates mutable view i2 and assign to it. I really don't like the cast in first line, maybe there is some function in std lib that encapsulates the cast and removes const modifier from type of variable, so this can be expressed in safe and idiomatic manner.

    Second way is to make ints mutable and private, then provide public accessor function:

    struct Foo {
    
      private int[2] _ints;
    
      this(int x, int y) {
          _ints = [x, y];
      }
    
      @property ref const(int)[2] ints () {
          return _ints;
      }
    }
    

    Compiler may be able to inline it.