Dynamically setting struct values from hash map

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 12 14:01:06 PDT 2016


On Thursday, 12 May 2016 at 20:52:46 UTC, Andrew Chapman wrote:
> I have seen the "allMembers" method from the traits module that 
> can give me the names of the struct fields, but I am unsure if 
> it's even possible to set the struct values using 
> variable/dynamic names.


Yes.

You can't loop over the hash and set values on the struct, since 
looping a hash is a run time operation, but you can loop over 
struct members.

So, the trick is to loop over the struct members (a compile-time 
operation) and set them (converting type with `std.conv.to` if 
necessary) if the value is in the hash.

foreach(member; __traits(allMembers, YourStruct))
   if(member in yourhash)
    __traits(getMember, your_object, member) = 
to!right_type(yourhash[member]);


basically, it is a bit more complex to filter out inappropriate 
fields and such, but that's the idea.

Check out the sample chapter of my book 
https://www.packtpub.com/application-development/d-cookbook to 
see more, you can get the reflection chapter free on that site.


More information about the Digitalmars-d-learn mailing list