Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created April 30, 2020 20:38
Show Gist options
  • Save rust-play/2394e6c48a42dc25a9be50f197e1fe5e to your computer and use it in GitHub Desktop.
Save rust-play/2394e6c48a42dc25a9be50f197e1fe5e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment