Reputation: 683
I'm currently trying to test some RAII code in Rust, and I'd like to delay dropping a value until a specific line of code.
In C#, GC.KeepAlive prevents an object from being garbage collected until after the call to GC.KeepAlive. The method is essentially a no-op from the perspective of the application, but it guarantees a valid reference to an object until a specific point in the code flow. It's mostly useful for testing.
Is there an idiomatic way to delay dropping a value until a certain point in Rust? I'm trying to test some RAII code, and I'd prefer to use a convention recognizable to another Rust programmer.
For example:
let foo = some_func();
// Force foo to be deallocated
// This line does something that, if foo were still alive, it would fail the test
some_other_func();
Upvotes: 0
Views: 223
Reputation: 76884
The easiest way to do this is to drop the object explicitly. When you call mem::drop
, the object is moved into that function, and therefore the object must exist in the caller before that point and not after that point. That signals to other Rust developers that you explicitly wanted destruction at that point. It doesn't necessarily indicate why you wanted destruction there, so you may still need a comment if it's not obvious from context.
For example, if you had a temporary directory and needed to keep it around:
extern crate tempfile;
fn do_something() {
let tempdir = tempfile::TempDir::new();
// Do some things with your temporary directory.
std::mem::drop(tempdir);
// Do some things without your temporary directory.
}
Upvotes: 1