Borrowing & References
Instead of transferring ownership, you can borrow values using references. A reference allows you to inspect or modify data without taking ownership of it.
Immutable References (&T)
Section titled “Immutable References (&T)”An immutable reference allows read-only access to a value. You can create multiple immutable references to the same data simultaneously.
fn calculate_length(&s: String) -> Int { return s.len()}
let name = "Flame Language"
// Pass `name` as an immutable referencelet len = calculate_length(&name)
// `name` remains fully valid and owned by `main`!print($"The string '{name}' has length {len}")Mutable References (&mut T)
Section titled “Mutable References (&mut T)”To modify a borrowed value in-place, pass a mutable reference using &mut:
fn append_exclamation(&mut s: String) { s.push_str("!")}
let mut greeting = "Hello"append_exclamation(&mut greeting)print(greeting) // "Hello!"The Borrowing Rules
Section titled “The Borrowing Rules”Flame’s compiler enforces two fundamental borrowing rules at compile time:
This prevents data races and iterator invalidation at compile time with zero runtime locks!
let mut data = "test"
let r1 = &data // OK: first immutable borrowlet r2 = &data // OK: second immutable borrow// let r3 = &mut data // ERROR: cannot borrow `data` as mutable while immutable references exist!