Skip to content

Docs/Language/Memory & Regions

Memory & Regions

Value and sharing rules, references checked by a borrow checker with no lifetime annotations, owned and borrowed strings, what the compiler frees, and regions.

~6 min read

On this page

Values and sharing

Every value is copied on assignment: numbers, structs, and Vec, HashMap and str too. The collections are reference-counted, so the copy shares its data until one side writes; after var b = a, a change to b does not show in a. == compares structs, enums and vectors by content.

struct Point { x: i64, y: i64 }

fn main() -> i64 {
    // Numbers and structs are copied on assignment
    var p = Point { x: 1, y: 2 };
    val q = p;
    p.x = 10;
    println(q.x);                 // 1

    // Vec, HashMap and str are values too
    var v: Vec<i64> = Vec::new();
    v.push(1);
    var w = v;
    w.push(2);
    println(v.len());             // 1: w is its own Vec
    println(w.len());             // 2
    return 0;
}

There is no general move checking: using a value after assigning or passing it on is allowed. A struct marked @linear can be used only once (Safety).

References

&x is a shared reference, &mut x an exclusive one. A function changes the caller’s collection through &mut:

fn add_one(buf: &mut Vec<i64>, x: i64) {
    buf.push(x + 1);
}

fn main() -> i64 {
    val x = 5;
    val r = &x;                   // shared reference
    println(*r);                  // 5

    var y = 10;
    val m = &mut y;               // exclusive reference
    *m += 5;
    println(y);                   // 15

    var b: Vec<i64> = Vec::new();
    add_one(&mut b, 41);
    println(b.get(0));            // 42
    return 0;
}

The borrow checker

A pass after type checking enforces the aliasing rules, with no lifetime annotations. It is on by default (--borrowck=off|warn|on).

  • Non-lexical lifetimes: a borrow ends at its last use.
  • Field-wise borrows: &s.x and &mut s.y can coexist.
  • Two-phase borrows: list.push(list.len()) is accepted.
  • Iterator invalidation: changing a Vec while a for loop walks it is rejected.
  • Field assignment: s.x = 1 while s is borrowed is rejected. Trait impl bodies and &v[i] are checked like any other code.
struct S { x: i64, y: i64 }

fn main() -> i64 {
    var v = 10;
    val r = &v;
    println(*r);                  // last use of r: the borrow ends here
    v = 20;                       // OK
    println(v);

    var s = S { x: 1, y: 2 };
    val a = &s.x;                 // field-wise borrows
    val b = &mut s.y;
    *b += 1;
    println(*a);

    var list: Vec<i64> = Vec::new();
    list.push(list.len());        // two-phase borrow
    println(list.len());
    return 0;
}

Output: 10, 20, 1, 1. Moving v = 20 before the last use of r is rejected:

error: borrow error in main (line 4): cannot mutate v: shared borrow(s) are active on it or its fields
    Held by: 'r' (&v, line 3).

Pushing to a Vec inside a for loop over it, and assigning a field of a borrowed struct, are rejected the same way:

struct S { x: i64, y: i64 }

fn main() -> i64 {
    var v: Vec<i64> = Vec::new();
    v.push(1);
    for x in v {
        v.push(x);        // error: the loop would read past a resize
    }

    var s = S { x: 1, y: 2 };
    val r = &s;
    s.x = 5;              // error: s is borrowed by r
    println(r.y);
    return 0;
}
error: borrow error in main (line 7): cannot change v while a `for` loop iterates over it: the loop would read past a resize or skip elements.
    Fix: collect the changes in another Vec and apply them after the loop.
error: borrow error in main (line 12): cannot assign to s.x: s is borrowed
    Held by: 'r' (&s, line 11).

References are second-class: they cannot be stored in structs, returned from a local, sent to another task, or captured by a closure that escapes.

fn bad() -> &i64 {
    val x = 5;
    return &x;
}
error: Reference error (line 3): in 'bad', 'bad' returns a reference to local 'x', which is freed when it returns

Owned and borrowed strings

str is an owned string and &str a borrowed one. A str field of a struct marked @scoped reads as &str: it belongs to the struct and may be freed with it. A borrowed string can be read, compared, printed, joined with + (the result is owned) and passed to a &str parameter. It cannot be returned as str, stored, or passed to a function’s str parameter; str_clone(s) makes an owned copy. A @scoped struct itself cannot be stored (in a field, global, collection or result) or sent to another thread.

@scoped
struct Request {
    path: str,
    body: str,
}

fn shout(s: &str) -> str {
    return s + "!";            // joining gives an owned str
}

fn route(r: Request) -> str {
    if r.path == "/hello" {
        return shout(r.body);
    }
    return str_clone(r.path);  // an owned copy can be returned
}

fn main() -> i64 {
    println(route(Request { path: "/hello", body: "hi" }));   // hi!
    println(route(Request { path: "/x", body: "" }));         // /x
    return 0;
}

Returning r.path directly is rejected:

error: Borrow error (line 7): returns a borrowed string (&str) as an owned str; the string belongs to its owner and may be freed after this returns.
    Fix: return str_clone(s) (an owned copy), or declare the result &str.

The http module’s http_serve_scoped(port, handler) passes each request to the handler as a @scoped ScopedRequest and frees the request’s memory after the response is sent. Because the handler cannot keep the request’s strings, this needs no unsafe.

What the compiler frees

There is no garbage collector. A variable owns its value, and the value is dropped when its scope ends; keeping a value somewhere else takes another owner, and parameters are borrowed. Strings, Vec buffers and Boxes are reference-counted. In practice:

  • a Vec, HashMap or str local: the old value when the variable is assigned again, the last one at the end of its scope;
  • a Vec<str> or Vec<Vec<T>> together with the elements it owns;
  • collections declared in a region block, at the end of the block;
  • string temporaries, where they are last used;
  • a local of a struct type with a drop method: the method is called at the end of its scope.

fid run --leaks lists anything that was never freed. One open case: a StringBuilder does not free its buffer yet.

Regions

A region name { } block scopes the names declared in it; using one after the block is a compile error (undefined variable 'x'). Collections declared in the block are freed at its end. region name with budget(N) { } adds up the sizes of the block’s declarations at compile time and rejects the program when they exceed N bytes.

fn main() -> i64 {
    region scratch {
        val x = 42;
        println(x);
    }
    return 0;
}

Run-time checks

Out-of-bounds indexes, integer overflow and double frees panic at run time, in release builds too. fid run --checked-alloc also faults on use after free or past a block’s end, and fid run --leaks lists blocks never freed, by where they were allocated.

Report an issue