您的位置 首页 > 腾讯云社区

【Rust问答】要如何实现一个全局变量的初始化(单例)---MikeLoveRust

//创建连接 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()); ... POOL.set(Pool::new(URL).unwrap()); let pool = POOL.get().unwrap();

lazy_static:

lazy_static!{ static ref POOL: Mutex = Mutex::new(Pool::new(URL).unwrap()); }

juzi5201314 2020-03-12 13:09

嗷打少了Lazy,OnceCell,Mutex的<Pool>

phper-chen 2020-03-12 13:25

?

作者 LayneYy 2020-03-12 13:57

谢谢啦,刚接触rust,还不太熟练这个风格的变成,我发现很多都需要依赖标准库之外的

alexlee85 2020-03-18 17:53

如果你初始化之后不更新你的单例变量的话没必要用Mutex吧

use std::sync::Arc; pub struct Pool { pub name: String, } pub fn establish_connection() -> Arc<Pool> { static mut POOL: Option<Arc<Pool>> = None; unsafe { Arc::clone(POOL.get_or_insert_with(|| { println!("init pool ~~~~~~~~~~~~"); Arc::new(Pool { name: "I'm a pool".to_string(), }) })) } } fn main() { let a = establish_connection(); println!("{}", a.name); let b = establish_connection(); println!("{}", b.name); }

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3cf7b2701b7901e3db01838f9dec26ba

---来自腾讯云社区的---MikeLoveRust

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: