最近在学习 rust ,想着用rust 实现一个单例 模式(单例 是 一种创建型的设计模式,它保证一个类只有一个实例,并提供一个全局访问点。但是rust 中没有 单例,而且所有变量都会检查所有权和生命周期) ,发现网上很多都是用第三方库实现的,这个是我琢磨出来的 一种单例的实现方式,欢迎各位大佬指教。
话不多说直接放具体代码了
详细代码
singleton_learn.rs
rust
#[derive(Clone, Copy, Debug)]
struct Sing {
i1: i32,
f1: f32,
u1: u32,
b1: bool,
}
pub struct Singleton {
str: &'static str,
age: i32,
sig: Sing,
isinit: bool,
}
pub static mut SINGLETON: Singleton = Singleton {
str: "11111",
age: 55,
sig: Sing {
i1: 1,
f1: 2.0,
u1: 3,
b1: true,
},
isinit: false,
};
impl Singleton {
pub fn set_str(&mut self, str: &'static str) {
self.str = str;
}
pub fn set_age(&mut self, age: i32) {
self.age = age;
}
pub fn set_sig(&mut self, sig: Sing) {
self.sig = sig;
}
pub fn get_str(&self) -> &'static str {
self.str
}
pub fn get_age(&self) -> i32 {
self.age
}
pub fn get_sig(&self) -> Sing {
self.sig
}
}
pub fn get_singleton() -> *mut Singleton {
unsafe {
let prt = &raw mut SINGLETON;
let pr = &mut *prt;
return prt;
}
}
pub fn get_singleton_ref() -> &'static mut Singleton {
unsafe {
let sng = &raw mut SINGLETON;
let s = &mut *sng;
return s;
}
}
#[test]
pub fn fn1() {
println!("age is {}", get_singleton_ref().get_age());
get_singleton_ref().set_age(7777777);
//get_singleton_ref().get_age();
println!("age is {}", get_singleton_ref().get_age());
unsafe {
let sng = get_singleton();
(*sng).set_str("22222");
(*sng).set_age(66);
(*sng).set_sig(Sing {
i1: 4,
f1: 5.0,
u1: 6,
b1: false,
});
println!("str is {}", (*sng).get_str());
println!("age is {}", (*sng).get_age());
println!("sig is {:#?}", (*sng).get_sig());
}
}
main.rs 里的调用
rust
fn main() {
design_patterns_learn::singleton_learn::fn1();
println!(
"age is {}",
design_patterns_learn::singleton_learn::get_singleton_ref().get_age()
);
design_patterns_learn::singleton_learn::get_singleton_ref().set_age(6666666);
println!(
"age2 is {}",
design_patterns_learn::singleton_learn::get_singleton_ref().get_age()
);
}