delegates, lambdas and functions pitfall
dom via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Sep 5 05:15:35 PDT 2016
I am about to write my own stupid and simple http client .. and i
have added a callback function that has the received content as a
parameter.
class AsyncHttpGet
{
this(string host, ushort port, string path, void
delegate(string) callback )
{ ... }
}
My first attempt was to write:
auto f = new AsyncHttpGet("www.dprogramming.com", 80,
"/index.php", (string content) => {
...
});
but this is does not work because my AsyncHttpGet takes a normal
delegate and this => seems to add nothrow @nogc @safe to my
delegate type.
The correct syntax is only marginally differnt, but took me quite
a while to figure out:
( the missing arrow )
auto f = new AsyncHttpGet("www.dprogramming.com", 80,
"/index.php", (string content)
{
... // this is of type function
});
i noticed that delegates are "more powerful" than functions. once
the passed function e.g. needs to capture a value from the
outside it becomes a delegate type. I have also read that a
delegate can contain a reference to a class method bound to an
instance.
int dummy = 0;
auto f = new AsyncHttpGet("www.dprogramming.com", 80,
"/index.php", (string content)
{
dummy = 1; // this is of type delegate
});
but what is the difference between a lambda (=>) and a
functions/delegates?
i think this is a major pitfall for newcomers, and should be
adressed somehow.
More information about the Digitalmars-d-learn
mailing list