Created
January 21, 2017 23:04
-
-
Save stevej/181f0fd1fe583f5183484e5fa0d2cb35 to your computer and use it in GitHub Desktop.
Lesson #3: Borrow Checker Challenge Nested Borrows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?181f0fd1fe583f5183484e5fa0d2cb35gist=