前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Rust问答】要如何实现一个全局变量的初始化(单例)

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

作者头像
MikeLoveRust
发布2020-03-25 18:11:39
2.5K0
发布2020-03-25 18:11:39
举报
代码语言:javascript
复制
//创建连接
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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吧

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Rust语言学习交流 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档