Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in rust to mark a type as non-droppable?

Tags:

rust

I would like to make it a compiler error to allow a type to be dropped, instead it must be forgotten. My use case is for a type the represents a handle of sorts that must be returned to its source for cleanup. This way a user of the API cannot accidentally leak the handle. They would be required to either return the handle to its source or explicitly forget it. In the source, the associated resources would be cleaned up and the handle explicitly forgotten.

like image 752
nate Avatar asked Jan 25 '23 01:01

nate


2 Answers

The article The Pain Of Real Linear Types in Rust mentions this. Relevant quote:

One extreme option that I've seen is to implement drop() as abort("this value must be used"). All "proper" consumers then mem::forget the value, preventing this "destructor bomb" from going off. This provides a dynamic version of strict must-use values. Although it's still vulnerable to the few ways destructors can leak, this isn't a significant concern in practice. Mostly it just stinks because it's dynamic and Rust users Want Static Verification.

Ultimately, Rust lacks "proper" support for this kind of type.

So, assuming you want static checks, the answer is no.

like image 171
nnnmmm Avatar answered Jan 31 '23 09:01

nnnmmm


You could require the user to pass a function object that returns the handle (FnOnce(Handle) -> Handle), as long as there aren't any other ways to create a handle.

like image 22
Solomon Ucko Avatar answered Jan 31 '23 09:01

Solomon Ucko