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;
}

int main(string[] args)
{
  // create
  auto zond = new Zond();
  // test output
  foreach (it; zond._items) {
    writeln(it);
  }
  return 0;
}
//-------------------------------------------------------
this method does not work:
Error: field _items initializing not allowed in loops or after labels.

OK! is expected - I read in a book  Alexandrescu.

Make a small change, I add a nested function "addItem":
//-------------------------------------------------------
module main;
import std.stdio;

class Zond {
  this() {
    void addItem(in int value) {
      _items ~= value;  // OK ,  why?
    }

    foreach (i; 1..4) {
      addItem(i);
    }
  }

  immutable(int[]) _items;
}

int main(string[] args)
{
  // create
  auto zond = new Zond();
  // test output
  foreach (it; zond._items) {
    writeln(it);
  }
  return 0;
}
//-------------------------------------------------------
This method initialization works. why?
I do not understand the difference.

Reply via email to