bhylu.com

Advertisements

Rust Mutable Borrowing

Make one mutation path explicit while its borrow is active.

How it works

A mutable reference allows changing a value through a borrowed access path. Rust prevents conflicting active accesses that could violate its borrowing rules. Non-lexical lifetimes can end a borrow after its last use, so the relevant boundary is not always the closing brace. Use focused mutation helpers rather than exposing several competing ways to update shared state.

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

mutable-borrowing.rs

fn main() {
    fn add_packet(count: &mut u32) { *count += 1; }
    let mut count = 7;
    add_packet(&mut count);
    assert_eq!(count, 8);
    println!("Updated packet count: {count}");
}

Expected result

Updated packet count: 8

The helper borrows the count mutably for the call and dereferences it to change the stored value. Once the helper returns, the original binding can be read again. The numerical example is bounded; a real untrusted count should use checked arithmetic as well as correct borrowing.

Primary technical reference: Rust documentation.