How get struct value by member name string ?

Steven Schveighoffer schveiguy at gmail.com
Fri Jun 2 16:23:37 UTC 2023


On 6/1/23 10:58 PM, John Xu wrote:

> Ok, thanks for all you gentlemen's help. I tried following function,
> now it works like C/C++/Python way:
> 
>      string getTMember(T t, string columnName) {
>          foreach(member; __traits(allMembers, T)){
>              if (member == columnName) {
>                  return __traits(getMember, mcu, member).to!string;
>              }
>          }
>          return "";
>      }
> 

You can use a switch, and the search for the right member name should be 
more optimized, though it's possible the compiler might recognize your 
pattern and do this anyway:

```d
string getTMember(T t, string columnName) {
    switch(columnName)
    {
         static foreach(member; __traits(allMembers, T)) {
             case member:
                  return __traits(getMember, t, member).to!string;
         }
         default:
             return "";
    }
}
```

This is a very common pattern in e.g. serialization libs in D.

-Steve


More information about the Digitalmars-d-learn mailing list