Thread overview
Dynamically setting struct values from hash map
May 12, 2016
Andrew Chapman
May 12, 2016
Adam D. Ruppe
May 12, 2016
Andrew Chapman
May 12, 2016
Hi guys, apologies for the silly question, but I come from the world of dynamic languages and I'm wondering if it's possible to set struct values basic on dynamic variables?

e.g.

struct Person {
   string firstName;
   string lastName;
}

void main() {
   string[string] map;

   map["firstName"] = "Homer";
   map["lastName"] = "Simpson";
}

Is it possible to iterate through the hash map and set the struct values using the key/value pairs?

Something like this:

e.g.
Person p1;

foreach(key,val; map) {
   p1[key] = val;
}

The problem I'm trying to solve is that I'm wanting to write a generic "model" class that can read a record from a database and populate a known struct from the database values.  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.

Any help will be greatly appreciated!
Cheers,
Andrew.

May 12, 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.
May 12, 2016
On Thursday, 12 May 2016 at 21:01:06 UTC, Adam D. Ruppe wrote:

> 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.

That's wonderful Adam, thank you!  I actually had your book previously bookmarked - I should probably buy it :-)