Skip to content

Instantly share code, notes, and snippets.

@sitag
Created February 15, 2017 01:41
Show Gist options
  • Save sitag/199483e38d42957144d3067c42555049 to your computer and use it in GitHub Desktop.
Save sitag/199483e38d42957144d3067c42555049 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
// escaping the borrow checker
fn test(h:&mut HashMap<String, i64>) -> &mut i64 {
{
let matched:Option<&mut i64> = h.get_mut("B");
if matched.is_some() {
// assignment to raw pointer side steps the borrow checker
let v:*mut i64 = matched.unwrap();
return unsafe { &mut *v };
// this will not compile, as borrow escapes the function
// let v:&mut i64 = matched.unwrap();
// return v
}
}
h.insert("B".to_owned(), -1);
return h.get_mut("B").unwrap();
}
fn main(){
let mut h:HashMap<String, i64> = HashMap::new();
h.insert("A".to_owned(), 1);
test(&mut h);
println!("{:?}", h);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment