Call drop() on shutdown
I know that rust itself does not call drop() on static instances; however, I wonder if this could be supported by once_cell.
My use case is that I need to clean some resources (e.g. stop a docker container) when the process exits.
For example:
struct DataWithDrop{
pub val: u32
}
impl Drop for DataWithDrop {
fn drop(&mut self) {
println!("dropping with val: {}", self.val)
}
}
fn global_with_drop() -> &'static Mutex<DataWithDrop> {
static INSTANCE: OnceCell<Mutex<DataWithDrop>> = OnceCell::new();
INSTANCE.get_or_init(|| Mutex::new(DataWithDrop{val: 1111111111}))
}
///
/// This test prints:
/// val is 1111111111
/// dropping with val: 222222222
///
/// I would like to print "dropping with val: 1111111111"
/// once all tests are executed.
///
#[test]
fn test_once_cell_drop() {
let _local = DataWithDrop{val: 222222222};
println!("val is {}", global_with_drop().lock().unwrap().val);
}
I would say that this is out of scope for once_cell. Moreover, I would also argue that the best pattern in this case is to create resources explicitly in main and pass references down:
- that way, you won't get shutdown order problem, when one global resource depends on another global resource
- shutdown usually involves error handing as well, so it's better to have explicit
fn finialize(self) -> io::Result<()>methods than to rely on implicitDrop, which has no affordance for error reporting.
@matklad I agree with every single word you said, anyway, my use case is explicitly about testing where I need to initialize something just once before all tests and to drop it at the end.
Closing: I think the way to solve this is to use something like https://crates.io/crates/shutdown_hooks, but that's better left to user-code/some other crate. I don't think this should be supported in once-cell proper.