Struct Initialization syntax

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jul 24 16:35:32 UTC 2018


On Tue, Jul 24, 2018 at 01:13:16PM +0000, Dukc via Digitalmars-d wrote:
> On Tuesday, 24 July 2018 at 12:37:21 UTC, Cym13 wrote:
> > That argument sounds quite dangerous to me, especially since my
> > experience is on the contrary that constructor arguments are often
> > named the same as the attribute they refer to. And what of mixed
> > cases? I really wouldn't rely on anything like naming conventions
> > for something like that.
> 
> I was going to ask that how can they be named the same since the
> argument would then shadow the member, but then I realized that this
> works:
> 
> struct S
> {   int a;
>     int b;
> 
>     this(int a, int b)
>     {   this.a = a;
>         this.b = b;
>     }
> }
> 
> Yes, you are right.

It works, but TBH it's quite a bad idea, and very confusing to read.

And TBH, if all the ctor is doing is copying its arguments to member
variables, then we really should be more DRY and have special syntax for
doing that, ala C++ (though the C++ syntax itself is pretty
pathological... D could use better syntax, but the idea remains: get rid
of redundancy like `this.a = a` or `a = _a`).


T

-- 
Старый друг лучше новых двух.


More information about the Digitalmars-d mailing list