rust singleton
모두가 사랑하는 싱글톤입니다. 러스트에서는 살짝 다르네요.
맞는지 모르겠지만 대강 해봅니다.
once_cell 이 cpp 의 call_once같은 기능인가 보네요
singletone 이고 억세스가 많을수 있으니 Mutex 도 추천되는것 같네요
use std::collections::HashMap;
use once_cell::sync::Lazy;
use std::sync::Mutex;
pub struct MyManager {
map: HashMap<String, String>,
}
// global static instance of MyManager
static INSTANCE: Lazy<Mutex<MyManager>> = Lazy::new(|| {
Mutex::new(MyManager {
map: HashMap::new(),
})
});
impl MyManager {
pub fn get_instance() -> &'static Mutex<MyManager> {
&INSTANCE
}
pub fn add_member(&mut self, key: String, value: String) {
self.map.insert(key, value);
}
pub fn get_member(&self, key: &str) -> Option<&String> {
self.map.get(key)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add_member() {
let my_manager = MyManager::get_instance();
{
let mut manager = my_manager.lock().unwrap();
manager.add_member("key1".to_string(), "value1".to_string());
}
let manager = my_manager.lock().unwrap();
assert_eq!(manager.get_member("key1"), Some(&"value1".to_string()));
}
}일단 테스트 코드까진 잘 도네요