Copy and Move
Copying and moving are operations a type has or does not have, and the compiler generates both: a copy duplicates a value's bytes, and a move is a byte copy followed by forgetting the source. Neither runs user code. What a type supports follows from what it holds, and two attributes take a capability away.
Copyable and move-only types
A type is copyable when it is plain data: it declares no destructor, every field, element and payload it holds is copyable, and it is not #NoCopy.
| Copyable | Move-only |
|---|---|
numbers, bool, characters, raw pointers | a type that declares a destructor ~T |
slices T[..] and var T[..], function values | a type holding a move-only field, element or payload |
structures, tuples, variants, unions, optionals, sums and arrays T[N] of copyable types | a #NoCopy or #NoMove type, and anything holding one |
= from a named copyable value copies its bytes. A type with a destructor owns resources, so copying its bytes would leave two owners to release them; it moves instead. Copyability is decided once per type, so a structure with a move-only field is move-only itself.
A named move-only source in any by-value position — a binding, argument, receiver, return, assignment, aggregate field, field shorthand or conditional arm — is an error without move. The help writes the transfer the way the position needs it:
error: cannot copy 'Text', which owns resources
note: a named value used by value in argument position is copied, and only plain data copies
help: write 'move text' to transfer it, or 'text.Clone()' to copy it
A #NoCopy type is reported as cannot copy 'Ticket', which prohibits copying, and its help offers the transfer alone. A fresh temporary — a call result, a literal, a constructor call — has no other owner and transfers without move.
Clone
A move-only value is duplicated only by an ordinary method, by convention Clone(&self) -> Self, called where the copy is wanted. Core::Cloneable is the interface that names it, so generic code duplicates a value under T: Cloneable:
struct Note {
text: String;
}
extend Note {
func Clone(&self) -> Self {
return Note { text: self.text.Clone() };
}
}
func Keep(note: &Note) -> Note {
return note.Clone(); // a fresh value: no 'move' needed
}
For String, Clone allocates, and running out of memory panics as every allocation in a collection or a string does.
= never runs user code. A copy operator with a body, func =(&var self, other: &T) { … }, is rejected:
error: custom copy hooks are not supported
help: implement 'func Clone(&self) -> Self' on 'T' and call it where a copy is needed
Assignment
Assigning over a live value is a replacement. The new value is produced first, then the old value is destroyed once, and then the new one is installed: value = MakeValue();, value = move other; and value = other.Clone(); each install a value nobody else holds. A field, a tuple element and an element of an array or a slice are destinations like any other — holder.item = move value and items[i] = move value destroy what the place held. A write through a raw pointer initializes the storage it addresses and destroys nothing.
Prohibiting copies
#NoCopy on a struct, variant or union makes it move-only even with no destructor. That suits plain data that must not be duplicated, such as a handle a destructor does not release:
#NoCopy
struct RoomKey {
room: int32;
}
func CheckOut(key: RoomKey) {}
func Main() -> int {
let key = RoomKey { room: 4 }; // a temporary: no 'move'
CheckOut(move key); // a named value: 'move'
return 0;
}
| Where | Refused | Written with a move |
|---|---|---|
| A binding | let spare = key; | let spare = move key; |
| An argument | CheckOut(key) | CheckOut(move key) |
| A return | return key; | return move key; |
| A field value | Booking { key: key } | Booking { key: move key } |
| A field shorthand | Booking { key } | Booking { key: move key } |
Prohibiting moves
#NoMove prohibits moving as well, so it implies #NoCopy. A value of such a type stays in the storage it was created in, which suits a value that points into itself; it is shared through a pointer or a reference. Moving one is an error:
error: moving type 'ListNode' is prohibited
Such a value is still created in place from a temporary, because nothing can have taken a temporary's address:
#NoMove
struct ListNode {
next: *var ListNode;
}
func IsLast(node: &ListNode) -> bool {
return node.next == null;
}
func Main() -> int {
let node = ListNode { next: null }; // built where it lives
PrintLine("{}", IsLast(node));
return 0;
}
Both attributes take no arguments, are written without parentheses, and may each be written once per declaration. They prohibit the capability everywhere, regardless of visibility.
A move operator with a body is rejected with custom move hooks are not supported and help: a type that must stay in place uses '#NoMove': a move never runs user code. The older bodyless declarations prohibit nothing:
error: a bodyless 'func =' does not prohibit copying
help: mark 'T' with '#NoCopy' instead
A bodyless func <- is rejected the same way in favour of #NoMove. A bodyless function in an interface is still an ordinary requirement.
Generic code
Generic code may copy a value of a type parameter only under T: Copyable; otherwise it moves the value, or calls Clone under T: Cloneable. A copy of an unbounded T is checked for each instantiation, and instantiating it with a move-only type reports the copy in the generic body:
error: cannot copy 'Owner', which owns resources
note: the generic code copies a 'T' here, which is 'Owner' in this instantiation
A T: Copyable bound moves the check to the call, which is refused for a move-only type argument: type argument 'Owner' does not satisfy interface bound 'Copyable' on type parameter 'T'. See Bounds.
Partial moves
A field, a tuple element or an array element cannot be moved out of a value on its own. A value that is partly there would leave nothing able to say what to destroy when its owner's scope ends, so a value is moved whole or not at all:
error: cannot move field 'gift' out of 'parcel', which is destroyed as a whole
note: partial moves would leave the aggregate with only some fields initialized when it is destroyed
help: move the complete aggregate or borrow or clone the component explicitly
The same error names a tuple element (field '0') and an array element (indexed element [0]). What works instead is taking the whole value apart with a moving destructuring pattern, so that every part gets exactly one new owner:
struct Item {
name: char8[..];
}
extend Item {
func ~Item(&var self) {
PrintLine("{} destroyed", self.name);
}
}
struct Parcel {
wrapping: Item;
gift: Item;
}
func Unwrap(parcel: Parcel) -> Item {
let Parcel { wrapping: _, gift } = move parcel;
return move gift;
}
- A part bound to a name belongs to that binding and is destroyed with it.
- A part bound to
_, or a structure field the pattern leaves out, has no owner left, so it is destroyed on the spot — at thelet, or at the top of amatcharm — in the order the parts appear in the pattern.
A destructuring let owns what it takes apart, so a named move-only value is handed to it with move; = parcel fails with cannot copy 'Parcel', which owns resources. Tuples may always be split this way. A structure may be split only when it declares no destructor of its own, because a destructor runs on the whole value:
error: cannot split 'Sealed' with a moving pattern, because it declares destructor '~Sealed'
note: '~Sealed' runs on the whole value, so no part of it can be taken out on its own
help: bind the whole value and read its fields, or match a value that stays with its owner
| You want | Write | Allowed when |
|---|---|---|
| one field, moved out | move parcel.gift | never |
| every part, each to one owner | let Parcel { wrapping: _, gift } = move parcel; | the structure has no destructor |
| to read a field | parcel.gift.name | always — reading moves nothing |
Matching and ownership
A match that binds parts of its subject takes them, the same way a destructuring let does. match move value { … } hands the subject over; a temporary subject, such as a Clone result, is taken directly. A match that binds from a named plain-data value without move matches a copy of it, which its arms own; the original stays with its owner. A match that binds nothing, or matches through a reference, takes nothing, and no binding over borrowed storage can be moved out. A named owning subject is matched with match move value, or as a clone with match value.Clone().
See also
- Ownership —
=,moveand fresh temporaries - Destructors — what replacement and splitting destroy
- Destructuring — the patterns a
lettakes apart - Constructors — making a value, as opposed to copying one
- Core interfaces —
CopyableandCloneable - Learn: Non-copyable types, Custom copy, Partial move
Overview
Every value has one owner. = copies plain data, move hands a value over, and the compiler rejects any read of a name whose value has moved away.
Destructors
A destructor, func ~T(&var self), runs exactly once for each value that still owns its state, newest value first, and makes its type move-only. Panics do not unwind.