Search⌘ K

Nested Functions, Structs, and Classes

Discover how to define and use nested functions, structs, and classes within inner scopes in D programming. Learn about encapsulation, closures, context pointers, and static nested definitions to manage memory and access control effectively.

Nested functions

Up to this point, we have been defining functions, structs, and classes in the outermost scopes (i.e., the module scope). They can be defined in inner scopes as well. Defining them in inner scopes helps with encapsulation by narrowing the visibility of their symbols, and creating closures, which we covered in the function pointers, delegates, and lambdas chapter.

As an example, the following outerFunc() function contains definitions of a nested function, a nested struct, and a nested class:

D
void outerFunc(int parameter) {
int local;
void nestedFunc() {
local = parameter * 2;
}
struct NestedStruct {
void memberFunc() {
local /= parameter;
}
}
class NestedClass {
void memberFunc() {
local += parameter;
}
}
// Using the nested definitions inside this scope:
nestedFunc();
auto s = NestedStruct();
s.memberFunc();
auto c = new NestedClass();
c.memberFunc();
}
void main() {
outerFunc(42);
}

Like any other variable, nested definitions can access symbols that are defined in their outer scopes. For example, all three of the nested definitions above are able to use the variables named ...