//创建连接
pub fn establish_connection() -> Arc<Pool> {
static mut POOL: Mutex<Option<Arc<Pool>>> = Mutex::new(None);
unsafe {
POOL.lock().unwrap().get_or_insert_with(||
{
println!("init pool ..");
Arc::new(Pool::new(URL).unwrap())
}
)
.clone()
}
}
Mutex::new(None); static 变量中又不允许出现 非 const fn,怎么能实现这个需求呢
---
juzi5201314 2020-03-12 12:51
这个需求的话,可以看看lazy_static和once_cell这个库
juzi5201314 2020-03-12 12:58
once_cell:
use once_cell::sync::Lazy;
static POOL: Lazy = Lazy::new(|| Pool::new(URL).unwrap());
...
POOL.xxxx;
use once_cell::sync::OnceCell;
static POOL: OnceCell= OnceCell::new();
...
let pool = POOL.get_or_init(|| Pool::new(URL).unwrap());
...
P