Struct Initialization syntax

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Jul 23 17:46:12 UTC 2018


On Mon, Jul 23, 2018 at 05:32:23PM +0000, aliak via Digitalmars-d wrote:
> On Monday, 23 July 2018 at 16:57:20 UTC, H. S. Teoh wrote:
> 
> > It's true that there's potential conflict with named arguments, but
> > IMO it's a mighty bad idea to name ctor parameters in a way that
> > conflicts with the struct fields.
> 
> After using Swift for a while, I've found this to be the exact
> opposite. It is on the contrary very common to name parameters as you
> would your members because they are very commonly the most intuitive
> names.
[...]

I worded myself poorly.  What I meant was that if a ctor parameter has
the same name as a field, then it's obviously meant to initialize that
field, so there isn't really a conflict, you're just passing the
argument to the ctor instead of setting it directly to the struct.  It
would be a horrendously bad idea to have a ctor parameter that has the
same name as a field, but is used to initialize a different field.

OTOH, if you have a ctor, then one would assume that you're
intentionally overriding direct initialization of fields, so you
wouldn't want people to be using named initialization of fields anyway,
they should be using the ctor instead.  So any conflicts in this area
wouldn't really be relevant.


> struct Point {
>   int x, int y;
>   this(x: int, y: int) {}
> }
> 
> auto p = Point(x: 3, y: 4); // what else would you name them?
> 
> Can we just consider that named struct init syntax *is* a generated
> named constructor?
> 
> If named arguments choose a different syntax then you have no
> conflict. If they go with the same (i.e. option 2) then you have
> seamless consistency.
[...]

Yes, this is what I was trying to get at.  Thanks!


T

-- 
Don't modify spaghetti code unless you can eat the consequences.


More information about the Digitalmars-d mailing list