Skip to content

Instantly share code, notes, and snippets.

@stevej
Created January 21, 2017 23:04
Show Gist options
  • Save stevej/181f0fd1fe583f5183484e5fa0d2cb35 to your computer and use it in GitHub Desktop.
Save stevej/181f0fd1fe583f5183484e5fa0d2cb35 to your computer and use it in GitHub Desktop.
Lesson #3: Borrow Checker Challenge Nested Borrows
// Nested borrows are a common source of trouble. This example is a bit contrived
// but illustrates the challenge.
fn main() {
let mut numbers = vec![1,2,3,4];
// Because push() needs a mutable borrow and len() needs an immutable borrow,
// the borrow checker lets you know you've broken the rules.
numbers.push(numbers.len());
println!("numbers has length {}", numbers.len());
}
/*
fn main() {
let mut numbers = vec![1,2,3,4];
// When nested incompatible borrows are needed, consider introducing a new binding.
// The type signature of Vec.len is fn len(&self) -> usize
// It needs an immutable borrow of self but returns a value you take ownership of.
// Therefore a new binding fits the bill nicely.
let length = numbers.len();
numbers.push(length);
println!("numbers has length {}", numbers.len());
// Further Reading: https://internals.rust-lang.org/t/accepting-nested-method-calls-with-an-mut-self-receiver/4588
}*/
@stevej
Copy link
Author

stevej commented Jan 21, 2017

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