I was playing around with d and i stuck in CaStore class, it accepts the user1 but not the user2 data, i get core.exception.RangeError@main.d(60): Range violation, for example to add db.ccuser[0] = user1;
without the [0] and next the db.ccuser[0] = user2;
without the [0]
import std.stdio;
class CAdata{ string username;}
class Users{
int age;
CAdata[] info;
this(){
setNull();
}
void setNull(){
age = 0;
info ~= new CAdata();
}
}
class CaStore{
Users[] ccuser;
this(){
ccuser ~= new Users();
}
}
void main()
{
Users user1 = new Users();
user1.age = 24;
user1.info[0].username = "bob";
Users user2 = new Users();
user2.age = 24;
user2.info[0].username = "alice";
CaStore db = new CaStore();
db.ccuser[0] = user1;
db.ccuser[1] = user2;
}
You are writing to a position in the array that is out of bounds.
When you declare your array
Users[] ccuser;
its length is initially 0
, there is no room for any elements. Then you append one element, yielding a length of 1
:
ccuser ~= new Users();
This is why the first line
db.ccuser[0] = user1;
works but the second one gives you an error:
db.ccuser[1] = user2;
You are writing to index 1
, but that is past the end of the array.
You can either:
Append to the array instead:
db.ccuser ~= user2;
Or increase the length of the array to make room:
db.ccuser.length = 2;
db.ccuser[1] = user2; // now there is room for two elements, no error