lwcas

rust borrow

· lwcas

what is “borrow” in rust?

borrow in rust is a way to use a value without taking ownership of it. instead of moving a value from one place to another, you can “borrow” it using references. this helps rust ensure memory safety without needing a garbage collector.

imagine you and a friend share a laptop with a draft document:

the result: many memory errors are caught before the program runs, so code is safer without needing a garbage collector.

how it works in practice

immutable borrow:

1let laptop = String::from("draft document"); // you own the laptop with the draft
2let viewer1 = &laptop; // friend1 opens in "view only" mode
3let viewer2 = &laptop; // friend2 also views at the same time
4println!("{}", viewer1);
5println!("{}", viewer2);

mutable borrow:

1let mut laptop = vec!["intro".to_string(), "body".to_string()]; // owner of the document parts
2let editor = &mut laptop; // one friend gets exclusive edit access
3editor.push("conclusion".to_string()); // friend edits the document
4println!("{:?}", editor);

more abstract &mut example showing immediate update and scope:

1let mut laptop = String::from("raft v1"); // owner
2{
3    let editor = &mut laptop; // exclusive edit session starts
4    editor.push_str(" — updated"); // changes happen immediately on the laptop
5    println!("{}", editor); // prints "draft v1 — updated"
6} // editor goes out of scope here
7println!("{}", laptop); // prints "draft v1 — updated" — owner can access again

example that will not compile:

1let mut laptop = String::from("draft v1");
2let editor = &mut laptop;
3// println!("{}", laptop); // error: cannot borrow `laptop` as immutable while `editor` (a mutable borrow) exists

why these rules exist

these rules prevent common mistakes like using something that was already removed or modifying something at the same time (which can cause unexpected behavior). they help rust guarantee memory safety at compile time.

memory safety means a program can’t read or write memory it shouldn’t. this prevents common bugs like:

extras

garbage collector: a garbage collector (gc) is a runtime component that automatically detects and reclaims memory a program no longer uses, so developers don’t have to manually free memory. this simplifies development but adds runtime overhead, potential pause times, and less predictable performance. rust instead provides deterministic, compile-time memory safety via ownership, borrowing, and lifetimes, dropping values at well-defined points without a gc.

#rust

Reply to this post by email ↪