struct initializer

Paul Backus snarwin at gmail.com
Wed Nov 29 16:48:09 UTC 2023


On Wednesday, 29 November 2023 at 16:38:36 UTC, Dom DiSc wrote:
> ```d
> struct S2 { int a; int b; this(int c, int d) { a=c; b=d; } }
>
> S2 fun3() { return S2( 5, 2 ); } // works but requires explicit 
> constructor
> ```

You can use this syntax without an explicit constructor:

     struct S3 { int a; int b; }

     S3 fun() { return S3(5, 2); }

The language spec calls this a [struct literal][1]. If you're 
using a new enough compiler, it even supports named arguments:

     S3 fun2() { return S3(b: 2, a: 5); }

[1]: https://dlang.org/spec/struct.html#struct-literal


More information about the Digitalmars-d-learn mailing list