Structs are Not Plain: A call for empty struct constructors

Dukc ajieskola at
Fri Sep 20 07:48:25 UTC 2019

On Thursday, 19 September 2019 at 09:02:39 UTC, FeepingCreature 
> We're doing unittesting with fixtures. A Fixture is a struct 
> that contains default values and mocks of the class structure 
> that is being tested. Unittests will have the form
> ```
> unittest {
>   with (Fixture()) {
>   }
> }
> ```

I think you should treat a struct like you would treat a D array. 
would you do:

> unittest {
>   with (new int[0]) {
>   }
> }

I don't think so. You would put something else than the array 
default value to the with statement.

Same goes for invariants. D code is not in an invalid state if 
`arr.length == 0 && arr.ptr == null` so an invariant would not 
check against that. Example of what is really invalid is 
`arr.length > 0 && arr.ptr != null` - that's the sort of thing 
invariants should check against, an instance that's not 
"honestly" null but is not fully constructed, or has impossible 

And for destructors. in this case, it would be something like:

for(auto elemPtr = ptr; elemPtr < ptr + length; elemPtr++) 

If the array is in the default value, it's empty and this 
destructor will do nothing. Same for struct destructors, they 
should work for "null" values, just not do anything they would 
normally do.

In fact, you need to do the above even if you never use `.init` 
values, as if you manually destroy on an instance, it will be set 
on the default value, and an another destructor will be run on it 
when it's lifetime ends.

I know this all has the downside that you cannot implement more 
complex "never null" types in a practical way. But in fact, most 
of D stuff has "null" anyway: floats, chars, arrays, pointers, 
classes regardless of the definition. Only bools, integrals and 
enums (if you don't define one) do not, none of which are complex 
types. The philosophy AFAIK is that a type should always provide 
a null value, if it can be assigned normally "wrong" values 
without enlarging it.

More information about the Digitalmars-d mailing list