Created
October 20, 2025 08:55
-
-
Save berkus/e444cce68921d4009376fcf07eb7cb64 to your computer and use it in GitHub Desktop.
Rust undroppable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // From https://jack.wrenn.fyi/blog/undroppable/ | |
| use std::mem; | |
| /// A type that cannot be dropped. | |
| pub struct Undroppable<T: ?Sized>(mem::ManuallyDrop<T>); | |
| impl<T> Undroppable<T> { | |
| // Makes `val` undroppable. | |
| // | |
| // If `val` has a non-trivial destructor, attempting | |
| // to drop it will result in a compilation error. | |
| pub fn new_unchecked(val: T) -> Self { | |
| Self(mem::ManuallyDrop::new(val)) | |
| } | |
| } | |
| impl<T:? Sized> Drop for Undroppable<T> { | |
| fn drop(&mut self) { | |
| const { | |
| assert!(!mem::needs_drop::<T>(), "This cannot be dropped."); | |
| } | |
| } | |
| } | |
| fn main() { | |
| let undroppable = Undroppable::new_unchecked(vec![1, 2, 3]); | |
| // commenting out this line results in a compilation error: | |
| core::mem::forget(undroppable); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment