Skip to content
rust单例共享
2025年6月13日 root

导入依赖

tom
[dependencies]
lazy_static = "1.4.0"  # 请确保使用最新版本

定义

rust
use tokio::sync::RwLock;
use std::sync::Arc;

#[derive(Clone)]
struct News {
    title: String,
    content: String,
}

lazy_static::lazy_static! {
    static ref NEWS_CACHE: Arc<RwLock<Vec<News>>> = Arc::new(RwLock::new(Vec::new()));
}

读写

rust
pub async fn get_news() -> Vec<News> {
    let cache = NEWS_CACHE.read().await;
    cache.clone()
}

pub async fn update_news(news: Vec<News>) {
    let mut cache = NEWS_CACHE.write().await;
    *cache = news;
}

Last updated: