Skip to content

Instantly share code, notes, and snippets.

@csknk
Forked from rust-play/playground.rs
Last active April 30, 2020 20:45
Show Gist options
  • Save csknk/2d72c1f411aa8bc54bb070a52b3de05e to your computer and use it in GitHub Desktop.
Save csknk/2d72c1f411aa8bc54bb070a52b3de05e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
/// 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(())
}
@csknk
Copy link
Author

csknk commented Apr 30, 2020

Rules for Variables

  1. Each value has a variable which is it's owner.
  2. There can only be one owner of a value at a time.
  3. When the owner goes out of scope, the value is dropped.

Rules of Borrowing

  1. Unlimited borrows for read-only borrows: let a = &x
  2. For a read only borrow, the original data is immutable for the duration of the borrow
  3. You can only have a single borrow at a time for mutable borrows: let a = &mut x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment