Borrowing
Borrowing lets a function or expression use a value without taking ownership. Vex's semantic checker tracks immutable and mutable references, moves, field access, and the lifetime of returned references.
Complete programs on this page print their computed values and return 0 for successful execution. Printed output and process exit status are separate: returning 42 from main(): i32 would report a nonzero process status, not print the number. Fragments without main belong inside a program.
Immutable references
An immutable reference uses &T:
struct Point {
public:
x: i32,
y: i32,
}
fn sum(point: &Point): i32 {
return point.x + point.y;
}
fn main(): i32 {
let point = Point { x: 3, y: 4 };
$println(sum(&point));
return 0;
}The callee can read through the reference, but it cannot mutate the borrowed value through an immutable reference.
Mutable references
A mutable reference uses &T!. The owner must be stored in a mutable binding:
struct Counter {
public:
value: i32,
}
fn increment(counter: &Counter!): i32 {
counter.value += 1;
return counter.value;
}
fn main(): i32 {
let! counter = Counter { value: 41 };
$println(increment(&counter!));
return 0;
}Use a mutable borrow only for the smallest operation that needs it. The exclamation mark at the call site makes the exclusive borrow visible.
The borrowing rule
At a point in the program, Vex permits several immutable borrows or one exclusive mutable borrow. An immutable and mutable borrow cannot conflict while both are live.
let! values = Vec.new<i32>()
let read_only = &values
use(read_only)
let writable = &values!
mutate(writable)The checker uses non-lexical lifetime reasoning. In the example, the immutable borrow can end after its last use, allowing the later mutable borrow.
References cannot outlive their source
A function may return a reference derived from one of its input references:
fn choose(left: &string, right: &string): &string {
if left.len() > right.len() {
return left
}
return right
}A reference to a local value cannot be returned:
fn invalid(): &i32 {
let value = 42
return &value
}The local value is destroyed when invalid returns, so the compiler rejects the dangling reference.
Returning references through known callbacks
A local function value can retain the declared function's return-source information. The result does not automatically borrow every argument:
struct Record { value: i32 }
fn first(left: &Record, right: &Record): &Record { return left; }
fn selected(source: &Record): &Record {
let local = Record { value: 719 };
let callback = first;
return callback(source, &local);
}Here first returns source, so its result has the source owner's lifetime. Passing another reference to the callback does not itself make that argument the returned pointee. Keep the callback's declaration and reference-returning contract clear at the call site.
This also works inside a generic forwarding function:
fn firstGeneric<T>(left: &T, right: &T): &T { return left; }
fn forward<T>(left: &T, right: &T): &T {
let callback: fn(&T, &T): &T = firstGeneric;
return callback(left, right);
}A generic forwarding function preserves the reference-source relationship; substituting a concrete T does not create a new owner. If a callback can return either input, both inputs must remain valid for every use of the result. A callback returning its second argument therefore cannot export the local Record from selected above. These are lifetime requirements on returned data, independent of how the callable is represented.
Writing and returning a stored reference
A stored reference refers to its pointee, not to the variable or field that holds the reference. Assigning a new reference changes the stored source:
struct StoredRecord { value: i32 }
struct StoredHolder { source: &StoredRecord }
fn replace(output: &StoredHolder!, source: &StoredRecord): &StoredRecord {
output.source = source;
return output.source;
}The returned reference comes from source; it does not borrow the storage of output. The write still imposes its normal lifetime requirements on the stored reference. A definite overwrite replaces the previous source. A write on only one branch, a possibly zero-iteration loop or a possibly aliasing index must retain every possible source. A reference copied before an overwrite keeps its original pointee.
Field-level access
The checker can reason about disjoint fields for supported struct operations:
struct Point {
public:
x: i32,
y: i32,
}
let! point = Point { x: 1, y: 2 }
let x_ref = &point.x
point.y = 10
use(x_ref)Access to point.y does not overlap point.x. A write to point.x while x_ref is live would be rejected.
A reference field's storage slot is distinct from the object it points to. Replacing holder.source does not mutate the old or new source object; ordinary scalar sibling updates and repeated field assignments use that same distinction. A live reference to the slot itself still prevents overwriting it.
References stored behind a live alias remain observable even when the original holder variable is no longer directly used. Their source cannot be mutated or destroyed while that alias can still observe it. This follows selected fields: an alias to one subobject does not automatically keep unrelated sibling references live, and an alias whose last use has passed does not extend a borrow. The conservative call-side and implicit-effect boundaries described above still apply. Copying a reference out of caller-owned storage does not borrow its reference slot; borrowing the slot with &holder.source does. Unknown pointees and whole-owner operations remain conservative.
Method receivers
Methods use the same reference types as ordinary functions:
fn (point: &Point) sum(): i32 {
return point.x + point.y
}
fn (point: &Point!) move_by(dx: i32, dy: i32) {
point.x += dx
point.y += dy
}The call-site value must satisfy the receiver's mutability requirement.
Borrowing an indexed element
For a source-defined index operator, exclusive use selects the declared mutable getter (&Container! -> &Element!). This applies to field assignment, an explicit mutable borrow, a contextually mutable reference argument, and a method whose selected receiver is &Element!:
struct IndexedCounter { value: i32 }
fn (self: &IndexedCounter!) increment() { self.value = self.value + 1; }
fn update(counters: &Vec<IndexedCounter>!) {
counters[0 as usize].increment();
let counter = &counters[0 as usize]!;
counter.increment();
}The same rule applies to user-defined containers and nested index projections; it is not a special privilege of Vec. The getter must return a mutable reference to the value required by the consuming operation. A getter returning a different element type cannot replace the value underneath an already resolved method call.
Selecting a mutable getter does not grant permission to mutate a shared owner, nor does it override a live conflicting borrow. A container with only a shared getter still cannot provide mutable element access. The selection is resolved at compile time and does not add runtime dispatch.
A freshly written &value can also take its shared/exclusive reference type from its consuming field or parameter. This applies after generic literal inference too. The borrow checker uses that inferred capability: if the field requires &T!, a simultaneous shared borrow of the same live pointee is not allowed. This does not upgrade an already stored &T reference to &T!.
Concurrency boundaries
References cannot be captured by a detached task when the capture could dangle or introduce an unsafe race:
let! values = Vec.new<i32>()
let borrowed = &values
go {
use(borrowed)
}Whether a capture is accepted depends on the lifetime and escape path. Prefer moving an owned value into a task or sending a value through a typed channel.
Container and foreign boundaries
An ordinary reference expresses a borrow. A raw pointer or foreign handle also needs its owning API's lifetime, invalidation, and synchronization rules. For example, a pointer into a Vec can be invalidated by growth, and a foreign callback may outlive the call that registered it. Keep such contracts at a small boundary and expose borrowed or owned Vex values to the rest of the program.
Guidance
- Prefer &T for read-only functions.
- Use &T! only when mutation is required.
- End borrows before taking a mutable borrow.
- Keep returned references tied to input data.
- Treat pointers, raw buffers, and FFI values as separate safety boundaries.
Next steps
- Ownership workflows — complete borrowed-parser and owned-report examples
- Ownership
- Lifetimes
- Memory Safety
- Concurrency Overview