how to access struct member using [] operator?

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Sep 25 02:16:00 PDT 2016


On Sunday, 25 September 2016 at 09:01:44 UTC, Namespace wrote:
> ----
> import std.stdio;
>
> struct Something
> {
>     int x, y;
>     float z;
>
>     auto opIndex()(string member) {
> 		switch (member) {
> 			case "x": return this.x;
> 			case "y": return this.y;
> 			case "z": return this.z;
> 			default: assert(0);
> 		}
>     }
> }
>
> void main(string[] args)
> {
>     Something s;
>     writeln(s["x"]);
>     writeln(s["z"]);
> }
> ----

Doesn't work. s["x"] is returned as float in this example. The 
reason is, opIndex cannot magically change return type based on 
the passed-in string.


More information about the Digitalmars-d-learn mailing list