Skip to content

Borrowing & References

Instead of permanently transferring ownership with a move, you can borrow access to values using references. A reference allows you to inspect or mutate data without taking ownership or triggering drops when the reference goes out of scope.


An immutable reference provides shared, read-only access to a place. You may create any number of simultaneous immutable references to the same data:

fn calculate_length(s: &String) -> Int {
return s.len()
}
let name = "Flame Language"
// Borrow `name` immutably
let len = calculate_length(&name)
// `name` remains fully valid and owned!
println($"The string '{name}' has length {len}")

To modify borrowed data in-place without taking ownership, create a mutable reference using &mut:

fn append_exclamation(s: &mut String) {
s.push_str("!")
}
let mut greeting = "Hello"
append_exclamation(&mut greeting)
println(greeting) // "Hello!"

Flame’s borrow checker statically enforces two invariants at compile time:

This rule eliminates data races across threads, aliased mutations, and iterator invalidation at compile time with zero runtime synchronization overhead:

let mut data = "test"
let r1 = &data // OK: shared immutable borrow
let r2 = &data // OK: second shared immutable borrow
// ❌ Compile Error: cannot borrow 'data' as mutable because it is also borrowed as immutable
// let r3 = &mut data

Place Projections & Disjoint Field Borrowing

Section titled “Place Projections & Disjoint Field Borrowing”

Flame’s borrow checker is place-aware. It tracks access paths down through struct fields and array indexes:

When two references target distinct, disjoint fields of a struct, Flame recognizes that their memory locations do not overlap. Both fields can be mutably borrowed at the same time:

struct User {
first_name: String,
last_name: String,
}
let mut u = User {
first_name: "John",
last_name: "Doe",
}
// ✅ Simultaneous mutable borrows to disjoint fields are safe:
let first = &mut u.first_name
let last = &mut u.last_name
first.push_str("athan")
last.push_str(" Senior")
println($"{u.first_name} {u.last_name}") // "Johnathan Doe Senior"

If two references target overlapping paths—such as the parent struct and one of its fields, or the exact same field twice—the compiler rejects the conflicting borrow:

let mut u = User { first_name: "John", last_name: "Doe" }
let parent_ref = &mut u
// ❌ Compile Error: cannot borrow 'u.first_name' as mutable more than once at a time
// let field_ref = &mut u.first_name

Flame statically guarantees that references can never outlive the data they point to. Attempting to return a reference to a local variable allocated on the stack produces an immediate compile-time diagnostic:

// ❌ Compile Error: cannot return reference to local variable 'x'
fn dangling_pointer() -> &Int {
let x = 42
return &x
}

By verifying lifetimes and place projections at compile time, Flame ensures 100% memory safety with zero garbage collection pauses.