gedaiu:

What i want to create, is an array structure like the one from PHP where array levels are not fixed and the sintax to access rhe values is val[][] so returning a reference to a struct that have the same type as the current type is useful.

there is a way to do this in D?

Instead of returning float as in my case, you return something else that has opIndex and opIndexAssign. This way you can pile up the []:


import std.stdio;

struct Foo {
    ref Foo opIndex(in size_t i) {
        writeln("opIndex: ", i);
        return this;
    }

    void opIndexAssign(in float value, in size_t i) {
        writeln("opIndexAssign: ", value, " ", i);
    }
}

void main() {
    Foo f;
    f[1] = 2;
    f[3][4] = 5;
    f[6][7][8] = 9;
}


That outputs:

opIndexAssign: 2 1
opIndex: 3
opIndexAssign: 5 4
opIndex: 6
opIndex: 7
opIndexAssign: 9 8

Bye,
bearophile

Reply via email to