matklad / once_cell

Rust library for single assignment cells and lazy statics without macros
Apache License 2.0
1.84k stars 110 forks source link

Call drop() on shutdown #98

Closed ufoscout closed 1 year ago

ufoscout commented 4 years ago

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);
}
matklad commented 4 years ago

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:

ufoscout commented 4 years ago

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

matklad commented 1 year ago

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.