bhylu.com

Advertisements

Rust Borrowing and References

Read an owned value through a temporary shared reference.

How it works

Borrowing lets code use a value without taking ownership. A shared reference provides read access while the original owner remains responsible for the value. References must remain valid for their use, and Rust checks many conflicting access patterns statically. Borrowing is useful for functions that only inspect input and do not need to keep an owned copy.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

borrowing.rs

fn main() {
    fn label_length(label: &str) -> usize { label.chars().count() }
    let label = String::from("north");
    assert_eq!(label_length(&label), 5);
    assert_eq!(label, "north");
    println!("Borrowed label; owner still usable");
}

Expected result

Borrowed label; owner still usable

The function accepts &str, which works with a String borrow and a string literal. It counts Unicode scalar values rather than byte length; neither operation necessarily counts user-perceived graphemes. The owner remains available after the call because no move occurred.

Primary technical reference: Rust documentation.