Ownership
Ownership and memory
Value semantics, moves, copies, access modes, cleanup and boxes: how Pelago manages memory with no garbage collector and no borrow checker.
Pelago has no garbage collector and no borrow checker. Every value has exactly one owner, values never share mutable state, and memory is released at a point you can read in the source. This chapter has one page per idea.
| Idea | What it answers | Page |
|---|---|---|
Value semantics, copy | What does b = a do? When do I get two values? | Values and copies |
| Moves | Which assignments give a value away, and what the compiler says if you use it again. | Moves |
| Read access | The default parameter mode: look, do not touch. | Read access |
inout and x! | Change the caller's variable in place. | inout |
sink and x!! | Take the value away from the caller. | sink |
deinit, scope exit, --leak-check | When values are released and how to run code at that moment. | Cleanup |
box<T> | A value on the heap: recursive types and indirection. | Boxes |
defer | Run a statement when a block ends. | defer |
The rules in one place
- A name owns its value. Two names never own the same value.
- Plain data (numbers,
bool,char, and structs and tuples made only of them) is copied by assignment. Data that owns memory (strings, lists, maps, boxes, and anything containing them) is moved by assignment. - A parameter is one of three modes: read (the default),
inoutorsink. The call repeatsinoutandsink(or the marks!and!!), so the effect of a call is visible without opening the function. - References exist only for the length of a call or statement. They cannot be stored, returned or captured, which is why there are no lifetime annotations.
- A value is released when its owner goes out of scope, running its
deinitif it has one. Nothing else frees memory.
Because two names never share one mutable value, a function cannot change your data behind your back, and tasks cannot race on it. See Concurrency.