对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.

参考

相关推荐
q5673152324 分钟前
Go语言多线程爬虫与代理IP反爬
开发语言·爬虫·tcp/ip·golang
Chandler2427 分钟前
Go语言即时通讯系统 开发日志day1
开发语言·后端·golang
有梦想的攻城狮38 分钟前
spring中的@Lazy注解详解
java·后端·spring
强化学习与机器人控制仿真1 小时前
openpi 入门教程
开发语言·人工智能·python·深度学习·神经网络·机器人·自动驾驶
野犬寒鸦1 小时前
Linux常用命令详解(下):打包压缩、文本编辑与查找命令
linux·运维·服务器·数据库·后端·github
明月看潮生2 小时前
青少年编程与数学 02-019 Rust 编程基础 08课题、字面量、运算符和表达式
开发语言·青少年编程·rust·编程与数学
huohuopro2 小时前
thinkphp模板文件缺失没有报错/thinkphp无法正常访问控制器
后端·thinkphp
天天打码2 小时前
Rspack:字节跳动自研 Web 构建工具-基于 Rust打造高性能前端工具链
开发语言·前端·javascript·rust·开源
Petrichorzncu2 小时前
Lua再学习
开发语言·学习·lua
AA-代码批发V哥2 小时前
正则表达式: 从基础到进阶的语法指南
java·开发语言·javascript·python·正则表达式