Reference Types

In this lesson, you will learn how variables of reference types maintain values.

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:

Press + to interact
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:

Press + to interact
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 types:

  • Reference variables do not ...

Get hands-on with 1400+ tech skills courses.