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

参考

相关推荐
爱吃山竹的大肚肚12 分钟前
@Valid校验 -(Spring 默认不支持直接校验 List<@Valid Entity>,需用包装类或手动校验。)
java·开发语言
汤姆yu22 分钟前
2026版基于python的协同过滤音乐推荐系统
开发语言·python
汤姆yu25 分钟前
基于python的电子商务管理系统
开发语言·python
我是大咖30 分钟前
C语言-贪吃蛇项目开发工具篇---ncursee库安装
c语言·开发语言
雨夜之寂40 分钟前
mcp java实战 第一章-第一节-MCP协议简介.md
java·后端
摇滚侠1 小时前
Spring Boot 3零基础教程,WEB 开发 Thymeleaf 核心语法 笔记39
spring boot·笔记·后端·thymeleaf
weixin_445476682 小时前
Java并发编程——synchronized的实现原理与应用
java·开发语言·并发·synchronized
yi碗汤园2 小时前
【超详细】C#自定义工具类-StringHelper
开发语言·前端·unity·c#·游戏引擎
sali-tec2 小时前
C# 基于halcon的视觉工作流-章49-网面破损
开发语言·图像处理·算法·计算机视觉·c#
YuanlongWang2 小时前
c# ABP vNext 框架详解及其模块化开发思想介绍
开发语言·c#