西安哪个公司可以做网站,湖南省智慧团建登录入口,可以直接玩游戏的网址,沉默是金歌曲原唱文章目录 rust处理全局变量的策略方法1#xff1a;在main中自动Drop全局变量 参考 rust处理全局变量的策略
Rust 的静态变量不会在程序退出时自动调用 Drop#xff0c;因为它们的生命周期与进程绑定。
use std::sync::OnceLock;struct GlobalData {content: String,
}impl … 文章目录 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: OnceLockGlobalData 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: OnceLockGlobalData 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.参考