Axle v0.22.0

Structs: copy and own

A struct is a value. Assigning one, passing it, returning it gives the receiver the fields, not a reference to them. That is simple while the fields are numbers. It stops being simple the moment a field holds an array: two struct values with the same field would name one array, and a write through either would show through the other.

Axle does not let that happen in silence. This page covers the rule, the two words that go with it, and what the compiler releases for you.

The rule in one table

The struct holdslet b = a;
only plain data — numbers, bool, char, string, enums without a payload, and structs made of thosecopies. a and b are independent
an array, an object or a Shared<T>, at any depthdoes not compile (E0794). Write copy a or own a

A line therefore has one meaning you can read without opening the struct’s declaration: it copies, or it tells you to choose.

struct Buf {
    pub data : i32[];
    pub len  : i32;
}

fn main() : i32 {
    let a = Buf { data: [1, 2, 3], len: 3 };

    let mut b = copy a;      // an independent value: `b.data` is its own array
    b.data[0] = 99;          // … so `a.data[0]` is still 1

    let c = own a;           // the value itself under a new name: `a` is dead
    return c.data[0] - 1;    // reading `a` here would be E0501
}
  • copy a builds a second value. a stays readable and the two never share storage.
  • own a moves the value. Nothing is duplicated; a is dead, and reading it afterwards is E0501. It takes a variable or a parameter — not a field and not an array element, because only a name can be dead.

The same choice is asked wherever a struct read out of one place lands in another: a let, an assignment, a field or element store, a member of a struct, array or tuple literal, a return of a field, and each branch of a c ? a : b or a match. A value built on the spot — a literal, a function’s result — has one name already and needs nothing.

copy is a word only in front of a value. A variable or a function you named copy keeps working.

What a copy duplicates

copy goes through the struct field by field:

FieldIn the copy
a number, bool, char, an enum without a payloadthe same value
stringits own string
T[] of numbersits own array, with the same contents
T[] of Shared<T>its own array; each element is shared with the source (the count goes up)
T[] of stringits own array, naming the same strings
Shared<T>the same object, shared (the count goes up)
an object of a class that declares clone()what clone() returns
another structcopied the same way, field by field
T[] of structs, or of objects whose class declares clone()its own array, each element copied in its turn
T \| null over a string, an array or an objectnull when the source is null, a copy of what is there otherwise

Everything else has no copy, and copy of a struct holding one is E0796: an object whose class declares no clone(), a function value, a Weak<T>, a nullable struct and an array of arrays. Such a struct can still be handed over with own.

A class says how it is copied

A struct of numbers is its bytes. An object is not: its constructor may register it somewhere, keep two fields in step, count instances. Copying it field by field would skip all of that, so the compiler does not guess. The class declares clone(), and copy calls it.

class Cell {
    pub v : i32;
    constructor(v : i32) { self.v = v; }
    pub fn clone(self) : Cell { return new Cell(self.v); }
}

struct Holder {
    pub cell : Cell;
    pub buf  : i32[];
}

fn main() : i32 {
    let h = Holder { cell: new Cell(11), buf: [1, 2] };
    let mut g = copy h;      // g.cell is h.cell.clone()
    g.cell.v = 12;           // … so h.cell.v is still 11
    return h.cell.v - 11;
}

The method takes nothing but self and returns the class. When the copy is one field after another through the constructor, @derive(Clone) writes it for you:

@derive(Clone)
class Tag {
    pub id : i32;
    constructor(id : i32) { self.id = id; }
}

struct Item {
    pub tag : Tag;
    pub n   : i32;
}

fn main() : i32 {
    let a = Item { tag: new Tag(7), n: 1 };
    let b = copy a;
    return b.tag.id - a.tag.id;
}

Return a new object from clone(). A clone() that returns self gives the copy the source’s object, and the compiler, unable to prove the copy owns it, leaves that object unreleased.

Passing a struct to a function

A function states in its signature what it does with a struct, and the caller writes the matching gesture.

struct Buf {
    pub data : i32[];
    pub len  : i32;
}

fn total(b : Buf) : i32 {            // reads it
    let mut t = 0;
    for (x of b.data) { t = t + x; }
    return t;
}

fn keep(own b : Buf) : i32 {         // takes it, and releases it on return
    return b.len;
}

fn main() : i32 {
    let a = Buf { data: [1, 2, 3], len: 3 };
    let t = total(a);                // lent: nothing is copied
    let k = keep(copy a);            // `keep` gets a value of its own
    let last = keep(own a);          // `keep` gets `a` itself; `a` is dead
    return t + k + last - 12;
}
The function declaresThe caller writesOtherwise
b : Buf — reads ittotal(a)total(copy a) is E0795: the function keeps nothing
own b : Buf — takes itkeep(copy a) or keep(own a)keep(a) is E0794: choose
mut b : Buf — writes itfill(a)the function writes the caller’s own value

Turning a parameter into own therefore fails every call that passed a bare variable, each with what to write. No call changes meaning quietly.

A plain parameter is lent for the length of the call. Storing it somewhere that outlives the call is E0513; declare it own if the function keeps it.

Who releases what a struct holds

You do not release anything. The compiler does, once, where the value’s life ends.

ValueReleased
a struct variablewhen it goes out of scope: each array, string and object it holds
a struct taken by an own parameterwhen that function returns, unless it handed the struct on
a struct handed on with ownby whoever holds it last
a field you overwrite (b.data = [8, 9];)the old array, at that line
an array of structseach element, then the array

Arrays of structs

An array of structs holds the structs themselves, one after another. When the array goes away, each element releases what it holds.

struct Buf {
    pub data : i32[];
    pub len  : i32;
}

fn make(n : i32) : Buf {
    return Buf { data: [n, n], len: 2 };
}

fn main() : i32 {
    let pair = [make(1), make(2)];           // two structs laid out in the frame

    let mut pool = new Buf[4];               // four empty slots on the heap
    pool[0] = make(3);
    pool[0] = make(4);                       // releases what slot 0 held
    pool[1] = Buf { data: [5], len: 1 };

    return pair[0].len + pool[0].len + pool[1].len - 5;
}                                            // every array is released here

A slot you never wrote is empty and costs nothing to release.

The array stays the owner through the ordinary uses: reading or writing a field of an element (pool[0].len, pool[0].data = [7];), passing an element or the whole array to a function that only reads it, and overwriting a slot at a computed position (pool[i % 2] = make(i);).

Reading an element whole is the same choice as anywhere else: let b = copy pool[0]; gives you a value of your own. own pool[0] is not accepted — an element is not a name.

Structs in collections

ArrayList<T>, HashMap<K, V> and HashSet<T> are written once for every T, so they cannot ask you to choose between copy and own for each element they move. A struct that holds an array, an object or a Shared<T> is refused as their element (E0604). A struct of plain data is refused too, for another reason: a collection compares its elements, and a struct has no equality (E0761). Use a plain array of the struct, or hold the data in a class and store Shared<T> handles (Collections → Collections of structs).

Errors you will meet

CodeYou wroteFix
E0794let b = a; — or a store, a returned field, an argument to an own parameter — on a struct that holds an array, an object or a Shared<T>write copy a or own a
E0795copy or own where it means nothing: on a value that is not a struct, own on a field or an element, or either one for a parameter that only readsdrop the word, or name a variable
E0796copy of a struct with a field that has no copydeclare clone() on the field’s class, hand the struct over with own, or hold the field as a Shared<T>
E0501a variable read after ownread it before, or copy it instead
E0604a collection of a struct that holds an array, an object or a Shared<T>a plain array of the struct, or Shared<T> elements
E0761a collection of a struct of plain datathe same

Each one is shown with its full message in Reading compiler errors.

Limits

LimitWhat happensWhat to do
copy of a struct holding a function value, a Weak<T>, a nullable struct or an array of arraysE0796build the new value field by field, or hand the struct over with own
A copied string[] names the same strings as the sourcethe array is the copy’s own; the strings are not duplicatednothing: replacing a slot in one array leaves the other as it was
An array of objects passed whole to a functionthe array is released, the objects in it are nothold the objects as Shared<T>, or keep the array in one function
A slot overwritten at a position that calls a function (pool[next()] = …)what the slot held is not releasedcompute the position into a variable first
copy and own on an array or an objectnot accepted; the words take a structan array is duplicated with [...xs], an object with its clone()

None of these frees anything twice. Where the compiler cannot prove it is the only owner, it leaves the storage allocated.

See also

memorystructcopyownownership