digitalmars.D - Suggestion: final struct initializers
- Mr T. (15/15) Dec 03 2020 Hello. Got a suggestion, not even a request: exhaustive struct
- Jacob Carlborg (4/23) Dec 04 2020 You can just use a constructor to achieve the same thing.
- Mr T. (2/3) Dec 04 2020 Constructors need writing, these things exist automatically.
- Q. Schroll (23/28) Dec 09 2020 True, but if you really need it multiple times, a mixin template
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?
Dec 03 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
Dec 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.
Dec 04 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: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/PMT1PTYou can just use a constructor to achieve the same thing.Constructors need writing, these things exist automatically.
Dec 09 2020