How get struct value by member name string ?

H. S. Teoh hsteoh at qfbox.info
Tue May 30 01:33:54 UTC 2023


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

-- 
Which is worse: ignorance or apathy? Who knows? Who cares? -- Erich Schubert


More information about the Digitalmars-d-learn mailing list