I want to create a mechanism that ensures resources are released, similar to how we can use drop
. However I want to enforce more complex constraints using Rust’s type system. I would like to ensure that the user satisfies some constraints before they can drop their object. One way we could with files is we could have a type File<T: ResourceState>
with
enum ResourceState {
OPEN,
CLOSED
}
then
impl Drop for File<OPEN> {
fn drop() {
panic("must close files");
}
}
This will ensure that we always close our files, but has this obvious downside of not finding this out until runtime then crashing the program. I want to figure this out at compile-time. An example of an ideal scenario:
fn main() {
let f: File<OPEN> = openf("file.txt")
// do stuff
// If we have '}' here it should result in a compiler error
// f is consumed safely and replaced with a File<CLOSED> object
let closed: File<CLOSED> = f.close();
// Safe to let closed go out of scope, no compile-error
}
Are there any existing mechanisms/macros that can accomplish this?