Created
January 9, 2018 19:48
-
-
Save tonyfinn/3703455ce6b3be0f880ba1efe1e9649c to your computer and use it in GitHub Desktop.
Lazy Loaded prevented by unexpectedly long lifetime
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
use std::collections::HashMap; | |
struct MyResult { | |
data: u32 | |
} | |
impl MyResult { | |
fn new(input: &String) -> MyResult { | |
let mut sum = 0u32; | |
// Assume this was an expensive calculation | |
for byte in input.as_bytes() { | |
sum += *byte as u32; | |
} | |
MyResult { | |
data: sum | |
} | |
} | |
} | |
struct ResultCache { | |
results: HashMap<String, MyResult> | |
} | |
impl ResultCache { | |
fn new() -> ResultCache { | |
ResultCache { | |
results: HashMap::new() | |
} | |
} | |
fn get_result_for(&mut self, input: &str) -> &MyResult { | |
let key = input.to_string(); | |
{ | |
// Immutable Borrow here | |
if let Some(result) = self.results.get(&key) { | |
return result | |
}; | |
// Immutable borrow should end here | |
} | |
// Prevents mutable borrow here | |
let results = &mut self.results; | |
let result = MyResult::new(&key); | |
results.insert(key.clone(), result); | |
results.get(&key).unwrap() | |
// Actually ends here | |
} | |
} | |
fn main() { | |
let mut rc = ResultCache::new(); | |
let result = rc.get_result_for("Hello"); | |
println!("{}", result.data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment