www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How add class or struct member after construction?

reply Marcone <marcone email.com> writes:
How add class or struct member after construction? Is it possible 
in D? How?
Nov 05 2020
next sibling parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Thu, Nov 05, 2020 at 10:48:38PM +0000, Marcone via Digitalmars-d-learn wrote:
 How add class or struct member after construction? Is it possible in
 D? How?
You can't, because D is statically-typed. However, you *can* implement something equivalent manually by other means, depending on your use case. What use do you have in mind? If you're more specific about what you're trying to accomplish, we could figure out a possible implementation for you. T -- Why waste time learning, when ignorance is instantaneous? -- Hobbes, from Calvin & Hobbes
Nov 05 2020
prev sibling next sibling parent Simen =?UTF-8?B?S2rDpnLDpXM=?= <simen.kjaras gmail.com> writes:
On Thursday, 5 November 2020 at 22:48:38 UTC, Marcone wrote:
 How add class or struct member after construction? Is it 
 possible in D? How?
This depends a lot on what you mean. The short answer is no - you cannot. However, given some limitations, it is possible. What sort of members do you need to add, and how will you be using them? For instance, this works: struct S { import std.variant; Variant[string] members; Variant opDispatch(string name)() { return members[name]; } Variant opDispatch(string name, T)(T value) { return members[name] = value; } } unittest { S s; s.foo = 13; assert(s.foo == 13); } -- Simen
Nov 05 2020
prev sibling parent Jacob Carlborg <doob me.com> writes:
On 2020-11-05 23:48, Marcone wrote:
 How add class or struct member after construction? Is it possible in D? 
 How?
It depends on what needs you have. You can declare a free function that takes the class/struct as the first parameter and call it like a method [1]: class Foo { int a; } void printA(Foo foo) { writeln(foo.a); } foo.printA(); printA(foo); The two above lines are exactly the same. [1] https://dlang.org/spec/function.html#pseudo-member -- /Jacob Carlborg
Nov 08 2020