Skip to content

Instantly share code, notes, and snippets.

@tonyfinn
Created January 9, 2018 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyfinn/3703455ce6b3be0f880ba1efe1e9649c to your computer and use it in GitHub Desktop.
Save tonyfinn/3703455ce6b3be0f880ba1efe1e9649c to your computer and use it in GitHub Desktop.
Lazy Loaded prevented by unexpectedly long lifetime
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