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

参考

相关推荐
k4m7v2pz16 小时前
34 天 33 个版本:rvs(rust-verb-shell)如何用版本号对抗 AI 误判
rust·shell·命令行工具·ai agent·系统信息·跨平台开发
05664616 小时前
Python高级——迭代器
开发语言·python·学习
初级代码游戏16 小时前
iOS开发 Swift 速记4:函数与闭包
开发语言·ios·swift
猿长大人16 小时前
C# | MediatR 入门指南:后端架构解耦
分布式·后端·架构·c#·.net
人间凡尔赛16 小时前
Kubernetes十周年:从Cloud Native到AI Native的架构范式跃迁
后端·云原生·架构
郭涤生16 小时前
C++ 零拷贝(Zero-Copy)
linux·开发语言·c++
回忆2012初秋16 小时前
C# 中的 EAP:基于事件的异步编程全面指南(一)
开发语言·c#
ty_xiumud16 小时前
以太网 MAC 详解:帧格式、位序、FCS 与收发流程
开发语言·macos·php
John jj17 小时前
拆解 Telegram 群组频道收录市场:三类方案,一个可运行的评分模型,目前TG中文人工评分加模型评分机制——LetsTG收录“快速”、“无门槛”
大数据·后端·python·深度学习·搜索引擎·django·全文检索
Boop_wu17 小时前
SpringBoot 集成阿里云短信认证服务(个人)
spring boot·后端·阿里云