Thread overview
Suggestion: final struct initializers
Dec 04, 2020
Mr T.
Dec 04, 2020
Jacob Carlborg
Dec 04, 2020
Mr T.
Dec 10, 2020
Q. Schroll
December 04, 2020
Hello. Got a suggestion, not even a request: exhaustive struct initializers.

Like this:

------------------------
struct Box {
    int x;
    int y;
}

void foo() {
    Box box = {x: 3};              // ok
    Box box = final {x: 3};        // error: y not initialized
    Box box = final {x: 3, y: 7};  // ok
}
------------------------

I'd appreciate this. What do you think?
December 04, 2020
On 2020-12-04 07:19, Mr T. wrote:
> Hello. Got a suggestion, not even a request: exhaustive struct initializers.
> 
> Like this:
> 
> ------------------------
> struct Box {
>      int x;
>      int y;
> }
> 
> void foo() {
>      Box box = {x: 3};              // ok
>      Box box = final {x: 3};        // error: y not initialized
>      Box box = final {x: 3, y: 7};  // ok
> }
> ------------------------
> 
> I'd appreciate this. What do you think?

You can just use a constructor to achieve the same thing.

-- 
/Jacob Carlborg
December 04, 2020
On Friday, 4 December 2020 at 15:25:13 UTC, Jacob Carlborg wrote:
>
> You can just use a constructor to achieve the same thing.

Constructors need writing, these things exist automatically.
December 10, 2020
On Friday, 4 December 2020 at 16:15:33 UTC, Mr T. wrote:
> On Friday, 4 December 2020 at 15:25:13 UTC, Jacob Carlborg wrote:
>>
>> You can just use a constructor to achieve the same thing.
>
> Constructors need writing, these things exist automatically.

True, but if you really need it multiple times, a mixin template can serve you well: A quick and easy one is

    mixin template FinalCtor()
    {
        this(typeof(this.tupleof) args)
        {
            this.tupleof[] = args[];
        }
    }

but error messages if you forget arguments are rather bad. You could (in increasing value but also increasing difficulty)
(1) Add a templated @disable'd overload that catches all others and generates a @disabled error message.
(2) Add @disable'd overload that are one or more arguments short.
(3) Use https://dlang.org/phobos/std_traits.html#FieldNameTuple and other reflection to actually insert the member names. That way, you can use named arguments as soon as the corresponding DIP is implemented and best error messages. This solution is very convoluted using string mixins and from a maintenance viewpoint is worse than (2).

I've done (2) in https://run.dlang.io/is/vAGRMV
and (3) in https://run.dlang.io/is/PMT1PT