How to construct a struct that does not explicitly define a constructor

Paul Backus snarwin at gmail.com
Sat Mar 1 00:47:20 UTC 2025


On Friday, 28 February 2025 at 23:31:23 UTC, Meta wrote:
> ```d
> struct Test
> {
>     int n;
>     float f;
>
>     static Test opCall(int n, float f)
>     {
>         return Test(n, f);
>     }
> }
>
> void main()
> {
>     Test(1, 2.0);
> }
> ```
>
> This code causes an infinite loop because the `Test(n, f)` 
> inside the static `opCall` is interpreted as a recursive call 
> to that same `opCall` function - not a call to the struct's 
> constructor (or however this is interpreted by the compiler 
> when there is no explicit struct/union constructor defined).
>
> I tried doing `return Test.__ctor(n, f)` but it says that 
> symbol doesn't exist. Is there any way to explicitly call the 
> struct's constructor so it doesn't cause an infinitely 
> recursive call to `opCall`?

You can't call the constructor because there isn't one.

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);
}
```


More information about the Digitalmars-d-learn mailing list