On Wednesday, 26 February 2025 at 03:47:32 UTC, Arredondo wrote:
Is it possible to declare a partially initialized struct?

I would have thought that doing it like this would work:

```
struct S {
    int[100] a = void;
    int b = 0;
}

```

But when I declare a variable of type `S`, the array `a` is initialized, so it seems that the `= void` is not playing any role here.

Of course `S s = void;` works for `a`, but then `b` is not initialized. I tried doing:

```
struct S {
        @disable this ();
        auto this(int b) {
                this.b = b;
                a = void;
        }
        
    int[100] a;
    int b = 0;
}
```
But that doesn't even compile.


I'm currently settling for something like:
```
auto placeS(string name)() => iq{
        S $(name) = void;
        $(name).b = 0;
}.text;
```
and then declare with `mixin(placeS!"s");`.

Is there a better way?

Cheers!
Arredondo.

I highly recommend you don't do that.
I've been using D for more than 5 years and that led me to a bug which took me some time to solve that quite recently.

The proper way to to do it is creating an implementation of a void init instead:

    ```d
    struct S
    {
        int[100] a;
        int b = 0;
        static S defaultInit(int b)
        {
           S s = void;
           s.b = b;
           return s;
        }
    }
    ```

Having `void` initialization on fields would be really unsafe and could break your code at any moment and that would be really hard to identify. With that you'll be able at least to fix that issue.

Reply via email to