Rules of Borrowing in Rust
rust
This is a personal note/reminder on borrowing rules in Rust.
Rules for Variables
- Each value has a variable which is it’s owner.
- There can only be one owner of a value at a time.
- When the owner goes out of scope, the value is dropped.
Rules of Borrowing
- Unlimited borrows for read-only borrows:
let a = &x
- For a read only borrow, the original data is immutable for the duration of the borrow
- You can only have a single borrow at a time for mutable borrows:
let a = &mut x
Example
/// Notes ownership and borrowing.
fn main() -> Result<(), &'static str> {
let mut a = [1,2,3,4];
println!("{:?}", a);
{
let b = &mut a[0..2];
// You can't access a at this point because it has been mutably borrowed
// from. The following line won't compile, with the error message:
// `cannot borrow `a` as immutable because it is also borrowed as mutable`:
// println!("a: {:?}", a);
println!("b: {:?}", b); // b: [1, 2]
b[0] = 42;
println!("b: {:?}", b); // b: [42, 2]
}
// a is accessible again:
println!("a: {:?}", a); // a: [42, 2, 3, 4]
Ok(())
}
comments powered by Disqus