Skip to content

Instantly share code, notes, and snippets.

@gliheng
Created December 14, 2017 12:36
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 gliheng/838f0cf9e18901564f3c2020976feb24 to your computer and use it in GitHub Desktop.
Save gliheng/838f0cf9e18901564f3c2020976feb24 to your computer and use it in GitHub Desktop.
use global static variable in rust
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);
});
}
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