digitalmars.D - Another syntax improvement idea
- ryuukk_ (54/54) Nov 26 2022 ```D
```D struct Option { alias cb_t = void function(string); string key; string alt; cb_t cb; string description; } void main() { // 1 Option[] options = [ Option( "-i", null, null, "ignore" ) ]; // 2 Options[] options = [ { key: "-i", description: "ignore" } ]; } ``` 1 - this is the current and only way to do it, i can't leverage D's default value, and i need to fill everything before i can fill the field i want It's not safe at all, you can't know what fields refer to what If i add a new field then i'm screwed since it's not longer in order If i have an array of many elements, then imagine having to reorder every single item.. 2 - this uses the C's designated initialization features for struct, it is nice when used in arrays because it's a succession of the same types, so you don't have to repeate yourself, you save lot of keystrokes and you no longer at the mercy of fields order, you are safe from all the problems from 1. You type the field name you want to set and you done, you can leverage D's default value feature This is already possible for initialization, i promote to relax this restriction so it can be used in arrays when the type is known for example Note: I liked Adam's proposal about leveraging `auto` in the Enum Type Inference DIP discussion thread, maybe it can be used here? ``auto { key: "-i", description: "ignore" }`` `alias` is not an option, `Option` is `Option`, it's not `O` or `Opt`, and the key is to leverage specifying the field name so it's readable and not bound to what ever field order it is What do you think, DIP worthy?
Nov 26 2022
Oops, actually the provided example works (when you fix the extra 's' for 2. my bad!) However, my code that lead me to write this post doesn't: ```D extern(C) void main(int argc, char**argv) { parse(argc, argv, [ // works // Option( "-n", (value) { }), // doesn't work { key: "-n", cb: (v) {} } ]); } struct Option { alias cb_t = void function(const(char)[]); const(char)[] key; cb_t cb; } void parse(int argc, char**argv, scope const Option[] options) { } ``` This one doesn't..
Nov 26 2022
On the IRC chat, named arguments was mentioned as a way to solve this `Option(key: "-i")` Hopefully it's still a planned feature, i like that one, even thought i still believe there is value for 2.
Nov 26 2022
On Saturday, 26 November 2022 at 18:19:33 UTC, ryuukk_ wrote:Hopefully it's still a planned feature, i like that one, even thought i still believe there is value for 2.I think it's worth it. Batch assignment of `D` arrays is much more troublesome than `C++`. Each one must have a `struct` name.
Nov 26 2022