On Thursday, 15 May 2014 at 16:13:59 UTC, AntonSotov wrote:
DMD 2.065
I do not know much English. sorry.

need to initialize immutable array  "_items"
//-------------------------------------------------------
module main;
import std.stdio;

class Zond {
  this() {
    foreach (i; 1..4) {
      _items ~= i;  // is expected ERROR
    }
  }

  immutable(int[]) _items;
}

You're only allowed to assign an immutable value in a constructor once, which is why it doesn't let you do so in a loop. As for the second example, that looks like a bug to me.

Here are a couple ways to initialize the array:

1:
  this() {
    import std.exception : assumeUnique;
    int[] items;
    foreach (i; 1..4) {
      items ~= i;
    }
    _items = items.assumeUnique;
  }

2:
  this() {
// The result of a pure function may be implicitly cast to immutable.
    _items = function() pure {
      int[] items;
      foreach (i; 1..4) {
        items ~= i;
      }
      return items;
    }();
  }

BTW, this would be better suited to the digitalmars.D.learn group.

Reply via email to