Static struct initialization syntax behavior & it being disabled upon adding a constructor

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Apr 18 03:21:30 UTC 2022


On Sun, Apr 17, 2022 at 05:35:13PM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
> On 4/17/22 08:13, HuskyNator wrote:
[...]
> > - 2: Why does adding a constructor to a struct disable the use of
> > the static initialization syntax?
> 
> I am not sure how to answer this question because I am about to say
> don't use the static initialization syntax. :/ To me, idiomatic way of
> constructing D objects is
> 
>   auto m = Mat!2([1,2]);
> 
> The reason why one cannot define a default constructor for a D struct
> is because every type in D must have a statically known .init value. A
> user-defined default constructor could not be known at compile time.

IME, when the lack of default ctors in D starts bothering me, that's
usually around the time the struct really ought to be rewritten as a
class (which *does* support default ctors).

Structs in D ought to be treated like "glorified ints", as Andrei puts
it. If you need complex ctors and complex methods, that's a sign you
should be using a class instead.


[...]
> Really, compared to C++, the amount of constructor, destructor, copy
> constructor, etc. that I do *not* write in D is very liberating to me.
> It feels like I just write what is needed and it mostly just works.
[...]

One thing about idiomatic D code is that it embraces the "create the
object first, then kick it into shape" philosophy, vs. the "meticulously
manage the initialization of every last bit in the ctor so that the
object comes out of the ctor call a perfect product ready to ship"
philosophy. The latter requires a lot of boilerplate and micromanagement
of object state; the former, when done well, leads to streamlined code
that gets its job done with a minimum of fuss.


T

-- 
Never criticize a man until you've walked a mile in his shoes. Then when you do criticize him, you'll be a mile away and he won't have his shoes.


More information about the Digitalmars-d-learn mailing list