Member Access Based On A Runtime String

Adrian Matoga via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 1 00:53:20 PST 2016


On Tuesday, 1 March 2016 at 05:05:40 UTC, Jack Stouffer wrote:
> In Python, I can do this:
>
>     my_obj = Obj()
>     string_from_func = func()
>     setattr(my_obj, string_from_func, 100)
>
> Say func() returns "member1" or "member2", the setattr would 
> then set either one of those to 100.
>
> Is there any equivalent in D?

struct Foo
{
	string foo = "dog";
	int bar = 42;
	int baz = 31337;
}

void set(P, T)(ref P p, string name, auto ref T value)
{
	foreach (mem; __traits(allMembers, P)) {
		static if (is(typeof(__traits(getMember, p, mem)) Q)) {
			static if (is(Q : T)) {
				if (mem == name) {
					__traits(getMember, p, mem) = value;
					return;
				}
			}
		}
	}
	assert(0, P.stringof ~ " has no member " ~ name);
}

unittest
{
	Foo foo;
	foo.set("bar", 15);
	assert(foo.bar == 15);
	foo.set("foo", "cat");
	assert(foo.foo == "cat");
}



More information about the Digitalmars-d-learn mailing list