ITPub博客

首页 > 数据库 > 数据库开发技术 > 【Rust问答】要如何实现一个全局变量的初始化(单例)

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

原创 数据库开发技术 作者:Rust语言中文社区 时间:2020-03-21 18:36:38 0 删除 编辑
//创建连接
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





原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-06-11

  • 博文量
    1769
  • 访问量
    718718