Search⌘ K
AI Features

Reference Types

Explore how reference types work in D programming. Learn the key differences between reference variables and reference types, how slices, class objects, and associative arrays behave as references, and how assignment affects them. Understand concepts like identity, aliasing, and null references to build a solid foundation in managing reference types.

Variables of reference types have individual identities, but they do not have individual values. They provide access to existing variables.

Slices as reference types

We have already seen this concept with slices. Slices do not own elements, they provide access to existing elements:

D
void main() {
// Although it is named as 'array' here, this variable is
// a slice as well. It provides access to all of the
// initial elements:
int[] array = [ 0, 1, 2, 3, 4 ];
// A slice that provides access to elements other than the
// first and the last:
int[] slice = array[1 .. $ - 1];
// At this point slice[0] and array[1] provide access to
// the same value:
assert(&slice[0] == &array[1]);
// Changing slice[0] changes array[1]:
slice[0] = 42;
assert(array[1] == 42);
}

Contrary to reference variables, reference types are not simply aliases. To see this distinction, let’s define another slice as a copy of one of the existing slices:

int[] slice2 = slice;

The two slices have their own addresses. In other words, they have separate identities:

D
import std.stdio;
void main() {
// Although it is named as 'array' here, this variable is
// a slice as well. It provides access to all of the
// initial elements:
int[] array = [ 0, 1, 2, 3, 4 ];
// A slice that provides access to elements other than the
// first and the last:
int[] slice = array[1 .. $ - 1];
int[] slice2 = slice;
assert(&slice != &slice2);
writeln(&slice," : ",&slice2);
}

The following list is a summary of the differences between reference variables and reference ...