On Wednesday, 22 February 2017 at 11:18:15 UTC, Martin
Tschierschke wrote:
On Tuesday, 21 February 2017 at 14:02:54 UTC, Jacob Carlborg
wrote:
[...]
Yes, this works, I would say this is the simplest:
MyStruct s;
foreach (index, name ; FieldNameTuple!MyStruct)
writefln("%s: %s", name, s.tupleof[index]);
If you want something more close to "send" in Ruby, you need
to use a string mixin, like this:
foreach (name ; FieldNameTuple!MyStruct)
writefln("%s: %s", name, mixin("s." ~ name));
The string mixin example works for methods, opDispatch and
similar as well. The tupleof example, the first one, works
only for fields.
Exactly what I was looking for, **thank you!**
Both ways of accessing the struct elements are very interesting,
giving an impression what is possible with D.
Is it possible to overwrite "toString" for all structs in one
step?
Regards mt.
Since structs are Plain-old Data and don't do inheritance, the
best option is a template mixin.
ie.
template mixin PrettyPrint
{
string toString()
{
// . . .
}
}
From there, you can mix it into any struct you want.
struct MyStruct
{
mixin PrettyPrint;
}
If you're familiar with Rails, this is similar to a Concern.