当前位置: 首页 > news >正文

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

文章目录

  • rust处理全局变量的策略
    • 方法1:在main中自动Drop全局变量
  • 参考

rust处理全局变量的策略

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

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.
}
Program is running...

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

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

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 scopeprintln!("Program is running...");
}

测试:

Program is running...
Cleanup executed on program exit.

eg:

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 scopeprintln!("Program is running...");
}
Program is running...
GlobalData::free...
Cleanup executed on program exit.

参考

http://www.lryc.cn/news/504704.html

相关文章:

  • Node.js教程入门第一课:环境安装
  • Visual Studio 使用 GitHub Copilot 扩展
  • 【Qualcomm】IPQ5018获取TR069 WiFi 接口Stats状态方法
  • 数字营销咨询,照亮企业营销数字化每一步
  • 修改vscode中emmet中jsx和tsx语法中className的扩展符号从单引号到双引号 - HTML代码补全 - 单引号双引号
  • 【Cmake】
  • Flutter 内嵌 unity3d for android
  • sqlite加密-QtCipherSqlitePlugin 上
  • 正交投影 (Orthographic Projection) 详解
  • 盛元广通畜牧与水产品检验技术研究所LIMS系统
  • 三维空间刚体运动4-1:四元数表示变换(各形式相互转换加代码——下篇)
  • PyTorch如何通过 torch.unbind 和torch.stack动态调整张量的维度顺序
  • 【Unity3D】报错libil2cpp.so找不到问题
  • 事件冒泡机制详解
  • 红米Note 9 Pro5G刷LineageOS
  • 6.3.1 MR实战:计算总分与平均分
  • ARM循环程序和子程序设计
  • 静态路由、RIP、OSPF、BGP的区别
  • 知识分享第二十八天-数学篇一
  • BigDecimal在进行除法运算时需要注意四舍五入的位置
  • 第二部分:进阶主题 14 . 性能优化 --[MySQL轻松入门教程]
  • Mac电脑设置鼠标的滚轮方向
  • 【LDAP】LDAP概念和原理介绍
  • Android系统(android app和系统架构)
  • Android HandlerThread、Looper、MessageQueue 源码分析
  • HTML知识点详解教程
  • [数据结构#1] 并查集 | FindRoot | Union | 优化 | 应用
  • 科研绘图系列:R语言绘制网络图和密度分布图(network density plot)
  • Linux中输入和输出基本过程
  • 使用 acme.sh 签发和自动续期 ssl https 证书