Struct initialization has no effect or error?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Oct 3 07:22:41 UTC 2019


On Wednesday, October 2, 2019 11:48:46 PM MDT Mike Parker via Digitalmars-d-
learn wrote:
> On Thursday, 3 October 2019 at 04:57:44 UTC, mipri wrote:
> > On Thursday, 3 October 2019 at 04:33:26 UTC, Brett wrote:
> >> I was trying to avoid such things since X is quite long in
> >> name. Not a huge deal... and I do not like the syntax because
> >> it looks like a constructor call.
> >
> > It is a constructor call, though. You can define your own as
>
> > well:
> Technically it's a struct literal. It's only a constructor if you
> define one, in which case struct literals no longer work. E.g.,
>
> struct Foo {
>      int x;
>
>      this(int a, int b) { x = a + b; }
> }
>
> Without the constructor, the literal Foo(10) would be valid, but
> with the constructor you'll get a compiler error.

Yeah. Syntactically, there's no real distinction, but the compiler doesn't
do something like generate a constructor for you, and unlike with a
constructor, you won't necessarily get errors if you do something like use
too few arguments. So, if you had

struct S
{
    int x;
}

auto s = S(42);

and then changed it to

struct S
{
    int x;
    int y;
}

auto s = S(42);

the code would continue to compile without complaint. And if you had
something like

struct S
{
    string s;
    int i;
}

auto s = S("hello", 42);

struct S
{
    string s;
    int foo;
    int i;
}

auto s = S("hello", 42);

you end up initializing the wrong members. The same if had

struct S
{
    int x;
    int y;
}

auto s = S(12, 99);

and changed it to

struct S
{
    int y;
    int x;
}

auto s = S(12, 99);

The fact that struct literals exist basically forces you to declare
constructors if you don't want to have to worry about breaking code by
rearranging member variables.

Personally, I think that using struct literals is just begging for bugs in
your code, so I never use them, and I always declare constructors. I wish
that struct literals weren't a thing at all, but some folks clearly like
them.

If using a struct literal with braces without providing the member names
gets deprecated like apparently Walter wants to do, then maybe using the
construction syntax for struct literals would be deprecated as well, which
would at least improve the situation. struct literals with member names are
still error-prone, but at least you then eliminate the bugs where you
initialize the wrong members and instead just get the ones where new members
end up with the default value whether it's appropriate or not.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list