Skip to content

Instantly share code, notes, and snippets.

@berkus
Created October 20, 2025 08:55
Show Gist options
  • Save berkus/e444cce68921d4009376fcf07eb7cb64 to your computer and use it in GitHub Desktop.
Save berkus/e444cce68921d4009376fcf07eb7cb64 to your computer and use it in GitHub Desktop.
Rust undroppable
// 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