How get struct value by member name string ?

John Xu 728308756 at qq.com
Tue May 30 08:46:43 UTC 2023


On Tuesday, 30 May 2023 at 01:33:54 UTC, H. S. Teoh wrote:
> On Tue, May 30, 2023 at 01:24:46AM +0000, John Xu via 
> Digitalmars-d-learn wrote:
>> On Monday, 29 May 2023 at 11:21:11 UTC, Adam D Ruppe wrote:
>> > On Monday, 29 May 2023 at 09:35:11 UTC, John Xu wrote:
>> > >     Error: variable `column` cannot be read at compile time
>> > 
>> > you should generally getMember on a variable
>> > 
>> > T t;
>> > __traits(getMember, t, "name")
>> > 
>> > like that, that's as if you wrote t.name
>> 
>> It seems I can't use variable as member name:
>> 
>>     struct T {int a; string name;}
>>     T t;
>>     string s = "name";
>>     writeln(__traits(getMember, t, s));
>> 
>> Above code fails to compile. Any help?
>
> Short answer:
>
> `s` must be known at compile-time.  Or more precisely, known at 
> the time of template expansion. In this case, use `enum`:
>
> 	enum s = "name";
>
>
> Long answer:
> 	https://wiki.dlang.org/Compile-time_vs._compile-time
>
>
> T


How to put above enum as a function parameter? Following code 
wouldn't work:

     string getTMember(T t, enum string memberName) {
         return __traits(getMember, t, memberName);
     }

My database table is very wide, with many columns. Above ddbc 
allows a struct
to map db returned data. Then if I want a member's value to show 
in vibe.d template,
how do I use a function to get it?


More information about the Digitalmars-d-learn mailing list