In accordance to the new DIP process you can find the full presentation of the change here: https://github.com/dlang/DIPs/pull/22

This DIP aims at providing better orthogonality and more importantly a way to have keyword arguments in the language at little cost and great benefit by extending static initialization to avoid having to declare a variable. It makes the following code legal:

    struct totalArgs {
        int tax;
        int discount;
    }

    int total(int subtotal, totalArgs args = totalArgs.init) {
        return subtotal + args.tax - args.discount;
    }

    unittest {
        assert(total(42) == 42);
        assert(total(42, totalArgs(tax: 50)) == 92);
        assert(total(42, totalArgs(discount: 20, tax: 50)) == 72);

        int defaultTotal(int subtotal) {
            immutable defaultSet = totalArgs(tax: 20);
            return total(subtotal, defaultSet);
        }
    }

Here is the rational as found in the DIP:

Static struct initialization has great properties:

- It is explicit using named attributes
- Order of declaration doesn't matter
- Not all attributes have to be specified

No function call provide those properties, and consequently no constructor can benefit from it either. Authorizing such struct initialization makes the
language more orthogonal and opens new doors.

The most interesting is to use structs to mimic keyword arguments for functions. By encapsulating possible arguments in a struct it is possible to use in-place initialization to provide a clean interface very similar to
keyword arguments such as seen in python or ruby.

As it stands now the way to provide complex argument set to a function is either to generate lots of constructors for the different cases which is messy or by setting a struct up before passing it to the function in a C-way fashion. This change provides ways to design better high-level interfaces.

Besides the change is completely retro-compatible in a nice way: the library itself is just defining an argument struct and using it in its function interface. Code using older compilers can setup the struct without in-place initialization and modern compilers benefit from a cleaner interface.

This change also helps interfacing C code that uses structs.


I'm convinced such a change would be great for D but only if properly reviewed, please don't hesitate to comment it.

Reply via email to