对rust的全局变量使用drop方法

文章目录

rust处理全局变量的策略

Rust 的静态变量不会在程序退出时自动调用 Drop,因为它们的生命周期与进程绑定。

rust 复制代码
use std::sync::OnceLock;

struct GlobalData {
    content: String,
}

impl Drop for GlobalData {
    fn drop(&mut self) {
        println!("Cleaning up: {}", self.content);
    }
}

static GLOBAL_DATA: OnceLock<GlobalData> = OnceLock::new();

fn main() {
    GLOBAL_DATA.get_or_init(|| GlobalData {
        content: "Hello, world!".to_string(),
    });

    println!("Program is running...");
    // When the program exits, the Drop implementation for GlobalData is called.
}
bash 复制代码
Program is running...

方法1:在main中自动Drop全局变量

全局变量的生命周期应该和main的程序生命周期是一样长的,所以可以在main中创建一个CleanUp局部对象,为CleanUp()实现Drop特征,在Drop()特征中,完成释放全局变量的资源的功能。

rust 复制代码
struct Cleanup;

impl Drop for Cleanup {
    fn drop(&mut self) {
	    //调用某些全局变量的释放方法 或者 C库中的方法
        println!("Cleanup executed on program exit.");
    }
}

fn main() {
    let _cleanup = Cleanup; // The `Drop` method will be called when `_cleanup` goes out of scope
    
    println!("Program is running...");
}

测试:

bash 复制代码
Program is running...
Cleanup executed on program exit.

eg:

rust 复制代码
use std::sync::OnceLock;

struct Cleanup;


impl Drop for Cleanup {
    fn drop(&mut self) {
    GlobalData::free();
        println!("Cleanup executed on program exit.");
    }
}

struct GlobalData {
    content: String,
}


impl GlobalData{
    
    pub fn free()
    {
        println!("GlobalData::free...");
    }
    
}


static GLOBAL_DATA: OnceLock<GlobalData> = OnceLock::new();

fn main() {

    GLOBAL_DATA.get_or_init(|| GlobalData {
        content: "Hello, world!".to_string(),
    });

    let _cleanup = Cleanup; // The `Drop` method will be called when `_cleanup` goes out of scope
    
    println!("Program is running...");
}
bash 复制代码
Program is running...
GlobalData::free...
Cleanup executed on program exit.

参考

相关推荐
Ws_7 小时前
C#学习 Day2
开发语言·学习·c#
杰克尼7 小时前
天机学堂复习总结(day03-day04)
java·开发语言·redis·elasticsearch·spring cloud
x***r1517 小时前
jdk-11.0.16.1_windows使用步骤详解(附JDK 11环境变量配置与验证教程)
java·开发语言·windows
luck_bor8 小时前
File类&递归作业
java·开发语言
武子康9 小时前
Java-07 深入浅出 MyBatis数据库一对多关系模型实战:表结构设计与查询实现
java·后端
花椒技术9 小时前
企业内部 Agent 落地复盘:Gateway、Skill 和二次确认如何串起受控业务执行
后端·agent·ai编程
我是一颗柠檬11 小时前
【MySQL全面教学】MySQL事务与ACID Day9(2026年)
数据库·后端·mysql
枕星而眠11 小时前
数据结构八大排序详解(一):四大简单排序
c语言·数据结构·c++·后端
IT_陈寒11 小时前
React useEffect闭包陷阱差点把我整失业了
前端·人工智能·后端
努力努力再努力wz12 小时前
【Qt入门系列】:按钮组件全解析:从 QAbstractButton 到快捷键事件、单选与复选机制
c语言·开发语言·数据结构·c++·git·qt·github