how to access struct member using [] operator?
pineapple via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Sep 25 03:44:38 PDT 2016
On Sunday, 25 September 2016 at 04:54:31 UTC, grampus wrote:
> Dear all
>
> For example, I have a struct
> struct point{int x;int y}
> point a;
>
> Is there an easy way to access x and y by using a["x"] and
> a["y"]
>
> I guess I need to overload [], but can't figure out how.
>
> Someone can help? Thank you very much
If they all share the same type, you can use a switch like
@Namespace suggested.
If the "x" and "y" strings are available at compile-time, you can
use a mixin.
auto getattr(string attr)(point a){
mixin(`return a.` ~ attr ~ `;);
}
auto x = a.attr!"x";
Otherwise, no. D types aren't dynamic in the same way that
Python's types are.
More information about the Digitalmars-d-learn
mailing list