On Wednesday, 2 October 2019 at 17:54:20 UTC, H. S. Teoh wrote:
On Wed, Oct 02, 2019 at 05:37:57PM +0000, Brett via Digitalmars-d-learn wrote:
struct X { int a; }

X[1] x;

x[0] = {3};

or

x[0] = {a:3};

fails;

This works:

        x[0] = X(123);


I'd knew I'd gotten the impression from somewhere that this was the recommended way to initialize structs, but it took me a while to find
it.

Learning D:

  auto ms1 = MyStruct(10, 11);// struct literal
  MyStruct ms2 = {10, 11};    // C-style, not preferred
  MyStruct ms3 = {b:11, a:10};// Named initializers

  ..

  Struct literals are convenient for simple types ...
  but they only allow for direct initialization of member
  variables. If more complex initialization is required, struct
  constructors should be used.

And then the impression was probably just from every single example
using the first form.

https://dlang.org/spec/struct.html#static_struct_init doesn't say that this is dispreferred in any way, nor does it emphasize that you can't use initialization syntax to assign to an already initialized variable (this is probably obvious to C types). But there are 'Best Practices' notes elsewhere in the page. This section could have one of those, to
say to just use the constructors.

Reply via email to