Created
December 14, 2017 12:36
-
-
Save gliheng/838f0cf9e18901564f3c2020976feb24 to your computer and use it in GitHub Desktop.
use global static variable in rust
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
thread_local!(static data: RefCell<HashMap<String, i32>> = RefCell::new(HashMap::new())); | |
fn main() { | |
let x = || { | |
data.with(|c| { | |
c.borrow_mut().insert("a".to_string(), 1); | |
}); | |
}; | |
let y = || { | |
data.with(|c| { | |
c.borrow_mut().insert("b".to_string(), 2); | |
}); | |
}; | |
x(); | |
y(); | |
data.with(|c| { | |
println!("{:?}", c); | |
}); | |
} |
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::cell::RefCell; | |
use std::collections::HashMap; | |
fn main() { | |
let data = RefCell::new(HashMap::new()); | |
let x = || { | |
data.borrow_mut().insert("a".to_string(), 1); | |
}; | |
let y = || { | |
data.borrow_mut().insert("b".to_string(), 2); | |
}; | |
x(); | |
y(); | |
println!("{:?}", data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment