< 返回版块

LayneYy 发表于 2020-03-12 12:43


//创建连接
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,怎么能实现这个需求呢

评论区

写评论
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

作者 LayneYy 2020-03-12 13:57

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

phper-chen 2020-03-12 13:25

👍 对以下内容的回复:

juzi5201314 2020-03-12 13:09

嗷打少了Lazy,OnceCell,Mutex的<Pool> 对以下内容的回复:

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 12:51

这个需求的话,可以看看lazy_static和once_cell这个库

1 共 6 条评论, 1 页