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

参考

相关推荐
亚比囧5 分钟前
Java基础--面向对象(二)
java·开发语言
乐观勇敢坚强的老彭13 分钟前
c++寒假营day05
开发语言·c++·算法
摸鱼的春哥15 分钟前
把白领吓破防的2028预言,究竟讲了什么?
前端·javascript·后端
枫叶丹415 分钟前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
shimly12345618 分钟前
(done) 速通 rustlings(20) 错误处理1 --- 不涉及Traits
rust
shimly12345620 分钟前
(done) 速通 rustlings(19) Option
rust
重生之后端学习21 分钟前
74. 搜索二维矩阵
开发语言·数据结构·算法·职场和发展·深度优先
@atweiwei24 分钟前
rust所有权机制详解
开发语言·数据结构·后端·rust·内存·所有权
树獭叔叔26 分钟前
05-从隐藏向量到文字:LM Head如何输出"下一个词"?
后端·aigc·openai
绝无仅有26 分钟前
计算机网络核心面试知识深入解析
后端·面试·架构