A reference gives a function temporary access to a value without transferring ownership. Borrow with `&` for read-only access or `&mut` when the function must change the value. Unlike a raw pointer, a reference cannot be manipulated with pointer arithmetic; its lifetime constrains how long the borrow remains valid. section 4.2.2 section 2.1.5
Read without taking ownership
`fn reverse(s: &str) -> String` accepts a borrowed string slice and returns a new string. Call it with a literal, as in `reverse("gfedcba")`, or borrow a `String`, as in `reverse(&String::from("gfedcba"))`. The function reads through the reference rather than taking ownership of the input. section 4.2.2
Change a caller-owned value
`fn reverse_inplace(s: &mut String)` accepts a mutable borrow. Its example collects the string’s characters into a vector, reverses them, clears the original string, and pushes the characters back. The caller uses `reverse_inplace(&mut value)` and retains ownership. Despite the name, this is not a zero-copy reversal: it uses temporary memory, and UTF-8 makes direct string manipulation less straightforward. section 4.2.2
Table 4.1 Summary of argument passing
|
Argument passed by
|
Prefix
|
Moved?
|
Ownership
|
Default use case
|
|---|---|---|---|---|
|
Reference
|
&
|
No
|
Retained by caller
|
The callee requires temporary access to a value.
|
|
Mutable reference
|
&mut
|
No
|
Retained by caller
|
The callee needs to mutate a value without ownership.
|
|
Value
|
N/A
|
Yes
|
Transferred to callee
|
The callee needs to obtain ownership of the value.
|
|
Mutable value
|
mut
|
Yes
|
Transferred to callee
|
The callee needs to obtain ownership and mutate the value.
|
Compare the four argument forms by whether ownership moves and whether the callee can mutate the value. section 4.2.3
Prefer a reference when the callee needs temporary access. Pass by value when it needs ownership; small primitive values are another common exception. The same choice applies to method receivers: `self` moves the value, while a reference receiver does not. A reference can also expose access to private interior data without handing over ownership or exposing the private object itself. section 4.2.3 section 7.8
















