Immutable Borrows
immutable_borrows.nr59 lines
immutable_borrows.nr· neuro
// Immutable borrows `&T`: a non-owning reference that lets a function read a value and
// leaves the caller its binding. `&x` borrows the place `x`. Borrowing never moves the
// value, and `&T` is itself `Copy`. Field and method access auto-deref through the borrow,
// and every built-in operator reads a borrowed operand as it reads an owned one.
struct Point {
x: i64,
y: i64
}
impl Point {
func sum(&self) -> i64 {
self.x + self.y
}
}
// `s` is borrowed, not moved: the caller's string stays valid.
func describe(s: &string) -> u64 {
s.len() // auto-deref: `.len()` on a &string
}
// Borrow a struct and read a field through the reference.
func read_x(p: &Point) -> i64 {
p.x
}
// Borrow a struct and call a method through the reference.
func read_sum(p: &Point) -> i64 {
p.sum()
}
// Compare and subtract through the borrows: no `*` is needed to read them.
func gap(a: &i64, b: &i64) -> i64 {
if a > b { a - b } else { b - a }
}
func main() -> i32 {
val msg: string = "Neuro"
val n: u64 = describe(&msg) // borrow: msg is NOT moved
val again: u64 = msg.len() // still valid: borrowing never consumes
val pt = Point { x: 3, y: 4 }
val px: i64 = read_x(&pt) // 3
val ps: i64 = read_sum(&pt) // 7
val direct: i64 = pt.sum() // pt still usable after being borrowed
val g: i64 = gap(&px, &ps) // 4
println("describe(&msg) = {n}")
println("msg.len() after = {again} (borrowing never consumes)")
println("read_x(&pt) = {px}")
println("read_sum(&pt) = {ps}")
println("pt.sum() after = {direct} (pt still usable)")
println("gap(&px, &ps) = {g}")
// n (5) + again (5) + px (3) + ps (7) + direct (7) + g (4) = 31, minus 31 → 0.
val balance = (n as i32) + (again as i32) + (px as i32) + (ps as i32) + (direct as i32) + (g as i32) - 31
println("balance = {balance}")
return balance
}
neuroc run immutable_borrows.nr
describe(&msg) = 5
msg.len() after = 5 (borrowing never consumes)
read_x(&pt) = 3
read_sum(&pt) = 7
pt.sum() after = 7 (pt still usable)
gap(&px, &ps) = 4
balance = 0