Skip to content
This repository has been archived by the owner on Jun 6, 2021. It is now read-only.

Note: Boxing Expressions

Alex Rønne Petersen edited this page Jun 5, 2013 · 2 revisions

The pointer type @ refers to memory that is stored on the garbage-collected heap. In order to create data on the GC heap, or copy it there, an expression of some sort is needed. Fortunately, @ can double as both a pointer type and an expression without ambiguities. @ is therefore also referred to as the boxing operator, which can take on multiple forms - various boxing expressions.

The first form of @ is simple:

let boxed_int : @int = @42:i;

Or more succinctly:

let boxed_int = @42;

This simply creates an immutable GC box containing a native integer.

Similarly, we could create a GC box containing a structure:

let boxed_foo = @new Foo { bar = 42 };

We could also copy a local variable:

let i = 42;
let boxed_int = @i;

The second form of @ creates a mutable box:

let boxed_mutable_int = @mut 42;
*boxed_mutable_int = 0;
assert boxed_mutable_int == 0;

The third form is used to create arrays:

let array = @[1, 2, 3];

This creates a box wherein three integers are embedded directly.

You might intuitively think that the third form is not actually special; surely, it is just like the first form, but the array is the value being boxed? Unfortunately, it's not that simple or elegant. An array 'value' wouldn't really make sense because it has no known size, so it can't be stored on the stack or in a structure. For that reason, arrays can only be stored in the heap, and the boxing syntax for them is a special case.

The fourth form is the mutable version of array boxing:

let mutable_array = @mut [1, 2, 3];
mutable_array.[0] = 0;
assert mutable_array == @[0, 2, 3];

That's all there is to the boxing operator.

Note that there's no equivalent to the boxing operator for the * and & pointer types. The former must be allocated explicitly, e.g. with malloc, while the latter is just a unified pointer type.

Clone this wiki locally