D language code question

Started by
2 comments, last by Aldacron 8 years, 8 months ago

protected string delegate() getTimePeriod()
{
immutable string[] months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

string path     = buildPath(this._config.path.officialDirectory, "test");

return delegate()
{
	auto time = Clock.currTime();
	return format("%s/%d/%s/savedData.log", path, time.year, months[time.month - 1], time.day);
};
}

My problem here, is the return type. Its a delegate. However, at the end of the function, I don't really understand what the delegate that is returned, points to.

I mean, format returns just a string, not an actual function. So the delegate points to...a string?

Advertisement

I'm not super familiar with D, but from similar languages I'm guessing that "getTimePeriod" returns a function (delegate) that returns a string, defined as follows:



auto time = Clock.currTime();
return format("%s/%d/%s/savedData.log", path, time.year, months[time.month - 1], time.day);

So if you were to write "getTimePeriod()()", you would get a string.


return delegate()

{

auto time = Clock.currTime();

return format("%s/%d/%s/savedData.log", path, time.year, months[time.month - 1], time.day);

};

The quoted section returns an anonymous function (which itself will return a string when called).

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

You can think of a delegate as something like this:


struct Delegate {
    void* context;
    void* funcPtr;
}

So when you return a delegate, you're returning an instance of a type similar to this struct. The context is what allows the delegate to access any variables that were in scope at the point the delegate was created. It's what distinguishes a delegate from a function pointer, which has no context.

This topic is closed to new replies.

Advertisement