Created
February 15, 2017 01:41
-
-
Save sitag/199483e38d42957144d3067c42555049 to your computer and use it in GitHub Desktop.
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; | |
// 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