views:

98

answers:

1

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?

+1  A: 

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.

Michal Minich
Thanks for the reply. Note that I didn't actually intend for it to be publicly visible -- I was just keeping the code simple to illustrate the problem :)
Peter Alexander
You meant good, but you did bad - I'm pretty sure you very well know that increased code visibility increases program complexity ;)
Michal Minich