Explain function syntax
Paul Backus
snarwin at gmail.com
Thu Sep 18 01:51:23 UTC 2025
On Wednesday, 17 September 2025 at 22:16:50 UTC, Brother Bill
wrote:
> Then there is another example with 'delegate' instead of
> 'function.
>
> ```
> import std.stdio;
>
> void main()
> {
>
> }
>
> alias Calculator = int function(int);
>
> Calculator makeCalculator()
> {
> int increment = 10;
> return value => increment + value; // ← compilation ERROR
> }
>
> ```
[Nested functions][1] that access local variables from their
enclosing function need to take an additional, hidden "context"
parameter in order to actually find those variables at runtime.
Because of this, they have a different calling convention than
"normal" functions. As a consequence, if you take a pointer to
one of these functions, you do not get a normal "function
pointer" type (which is represented by the `function` keyword),
but a special ["delegate" type][2], which contains both a pointer
to the function itself, and a pointer to the context needed to
call it successfully.
[1]: https://dlang.org/spec/function.html#nested
[2]: https://dlang.org/spec/function.html#closures
More information about the Digitalmars-d-learn
mailing list