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 holds | let b = a; |
|---|---|
only plain data — numbers, bool, char, string, enums without a payload, and structs made of those | copies. a and b are independent |
an array, an object or a Shared<T>, at any depth | does 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 abuilds a second value.astays readable and the two never share storage.own amoves the value. Nothing is duplicated;ais dead, and reading it afterwards isE0501. 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:
| Field | In the copy |
|---|---|
a number, bool, char, an enum without a payload | the same value |
string | its own string |
T[] of numbers | its 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 string | its 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 struct | copied 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 object | null 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 declares | The caller writes | Otherwise |
|---|---|---|
b : Buf — reads it | total(a) | total(copy a) is E0795: the function keeps nothing |
own b : Buf — takes it | keep(copy a) or keep(own a) | keep(a) is E0794: choose |
mut b : Buf — writes it | fill(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.
| Value | Released |
|---|---|
| a struct variable | when it goes out of scope: each array, string and object it holds |
a struct taken by an own parameter | when that function returns, unless it handed the struct on |
a struct handed on with own | by whoever holds it last |
a field you overwrite (b.data = [8, 9];) | the old array, at that line |
| an array of structs | each 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
| Code | You wrote | Fix |
|---|---|---|
E0794 | let 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 |
E0795 | copy 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 reads | drop the word, or name a variable |
E0796 | copy of a struct with a field that has no copy | declare clone() on the field’s class, hand the struct over with own, or hold the field as a Shared<T> |
E0501 | a variable read after own | read it before, or copy it instead |
E0604 | a collection of a struct that holds an array, an object or a Shared<T> | a plain array of the struct, or Shared<T> elements |
E0761 | a collection of a struct of plain data | the same |
Each one is shown with its full message in Reading compiler errors.
Limits
| Limit | What happens | What to do |
|---|---|---|
copy of a struct holding a function value, a Weak<T>, a nullable struct or an array of arrays | E0796 | build the new value field by field, or hand the struct over with own |
A copied string[] names the same strings as the source | the array is the copy’s own; the strings are not duplicated | nothing: replacing a slot in one array leaves the other as it was |
| An array of objects passed whole to a function | the array is released, the objects in it are not | hold 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 released | compute the position into a variable first |
copy and own on an array or an object | not accepted; the words take a struct | an 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
- Language tour → Structs —
declaring a struct, literals, defaults and
..base. - Memory model → Ownership keywords —
borrowed,
mutandownparameters for every type. Shared<T>reference counting — when a value needs several owners.- Generics and traits →
@derive—@derive(Clone)and the other derivable traits. - Reading compiler errors —
E0794toE0796in full.