Search code examples
functionddefinition

Can you define functions inline in D?


I am wanting to do something like this:

void function() test = void function() { ... };

Is this possible? Also can I make function arrays like this:

void function()[] test = [
    void function() { ... },
    void function() { ... }
];

I know I could just use function pointers, but for my purpose the functions don't actually need a name, and will only be accessed from the array, so it seems quite redundant to give each one of them a declaration.


Solution

  • Yup, and you almost guessed the syntax. In the function literal, "function" goes before the return type:

    void function() test = function void () {...};
    

    Much of that is optional. This does the same (as long as the compiler can infer everything):

    auto test = {...};
    

    Further reading: http://dlang.org/expression.html#FunctionLiteral, http://dlang.org/function.html#closures


    Also, you can just nest functions in D:

    void main()
    {
        void test() {...}
        test();
    }