用Rust实现单例
  3Vc6H13Lg7Nk 15天前 26 0

1. 使用Arc + Mutex

在这个例子中,我们使用了 Arc (原子引用计数)和 Mutex (互斥锁)来实现线程安全的单例。通过 get_instance 方法,我们可以获取到单例实例,并对实例进行操作。

use std::sync::{Arc, Mutex};

struct Singleton {
    // 单例数据
    data: String,
}

impl Singleton {
    // 获取单例实例的方法
    fn get_instance() -> Arc<Mutex<Singleton>> {
        // 使用懒加载创建单例实例
        // 这里使用了 Arc 和 Mutex 来实现线程安全的单例
        // 只有第一次调用 get_instance 时会创建实例,之后都会返回已创建的实例
        static mut INSTANCE: Option<Arc<Mutex<Singleton>>> = None;
        unsafe {
            INSTANCE
                .get_or_insert_with(|| {
                    Arc::new(Mutex::new(Singleton {
                        data: String::from("Singleton instance"),
                    }))
                })
                .clone()
        }
    }
}

fn main() {
    // 获取单例实例
    let instance1 = Singleton::get_instance();
    let instance2 = Singleton::get_instance();
    // 修改单例数据
    {
        let mut instance = instance1.lock().unwrap();
        instance.data = String::from("Modified singleton instance");
    }
    // 输出单例数据
    {
        let instance = instance2.lock().unwrap();
        println!("{}", instance.data);
    }
}

 

2. 使用lazy_static的懒加载

使用 lazy_static crate: lazy_static crate 是一个常用的 Rust crate,可以实现懒加载的全局静态变量。通过 lazy_static ,可以在需要时创建单例实例,并确保只有一个实例被创建:

use lazy_static::lazy_static;
   use std::sync::Mutex;
    struct Singleton {
       // 单例数据
       data: String,
   }
    lazy_static! {
       static ref INSTANCE: Mutex<Singleton> = Mutex::new(Singleton {
           data: String::from("Singleton instance"),
       });
   }
    fn main() {
       // 获取单例实例
       let instance = INSTANCE.lock().unwrap();
       println!("{}", instance.data);
   }

3. 使用once_cell crate

使用 once_cell crate: once_cell crate 是另一个常用的 Rust crate,可以实现懒加载的全局静态变量。通过 once_cell ,可以在首次访问时创建单例实例,并确保只有一个实例被创建:

use once_cell::sync::Lazy;
    struct Singleton {
       // 单例数据
       data: String,
   }
    static INSTANCE: Lazy<Singleton> = Lazy::new(|| Singleton {
       data: String::from("Singleton instance"),
   });
    fn main() {
       // 获取单例实例
       let instance = INSTANCE.clone();
       println!("{}", instance.data);
   }

4. 使用 Rc 和 RefCell

使用 Rc 和 RefCell : Rc 是 Rust 标准库中的引用计数类型, RefCell 是一个提供内部可变性的类型。结合使用 Rc 和 RefCell ,可以实现简单的单例模式:

use std::rc::Rc;
   use std::cell::RefCell;
    struct Singleton {
       // 单例数据
       data: String,
   }
    fn main() {
       // 创建单例实例
       let instance = Rc::new(RefCell::new(Singleton {
           data: String::from("Singleton instance"),
       }));
        // 获取单例实例
       let borrowed_instance = instance.borrow();
       println!("{}", borrowed_instance.data);
   }    

 

原文:https://blog.csdn.net/u013769320/article/details/132094193

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 15天前 0

暂无评论

推荐阅读
  qn1eRyGNKz7T   2024年02月27日   77   0   0 Rust
  qn1eRyGNKz7T   2024年02月29日   60   0   0 Rust
  qn1eRyGNKz7T   2024年03月07日   58   0   0 Rust
  qn1eRyGNKz7T   2024年03月19日   81   0   0 Rust
  qn1eRyGNKz7T   2024年02月29日   61   0   0 Rust
  qn1eRyGNKz7T   2024年03月25日   89   0   0 Rust
  qn1eRyGNKz7T   2024年04月01日   102   0   0 Rust
  qn1eRyGNKz7T   2024年03月13日   76   0   0 Rust
  YqbaJkf98QJO   2024年02月20日   41   0   0 Rust
  3Vc6H13Lg7Nk   15天前   26   0   0 Rust
  qn1eRyGNKz7T   2024年02月23日   80   0   0 Rust