How to construct a struct that does not explicitly define a constructor
Meta
jared771 at gmail.com
Sat Mar 1 02:19:55 UTC 2025
On Saturday, 1 March 2025 at 00:47:20 UTC, Paul Backus wrote:
> What you can do is use curly-brace initialization syntax:
>
> ```d
> struct Test
> {
> int n;
> float f;
>
> static Test opCall(int n, float f)
> {
> Test result = { n, f };
> return result;
> }
> }
>
> void main()
> {
> auto test = Test(1, 2.0);
> assert(test.n == 1);
> assert(test.f == 2.0);
> }
> ```
Thanks, I forgot about that syntax. Another question I have is if
there's a way to do this inline:
```d
struct Test
{
int n;
float f;
static Test opCall(int n, float f)
{
//return {n, f}; Error
//return Test {n, f}; Error
//return {n: n, f: f}; Error
//return Test {n: n, f: f}; Error
}
}
void main()
{
auto test = Test(1, 2.0);
assert(test.n == 1);
assert(test.f == 2.0);
}
```
More information about the Digitalmars-d-learn
mailing list