capypad
0 day streak
rust / expert
Snippet

Optimizing with UnsafeCell

'UnsafeCell' is the only legal way to obtain a mutable reference from an immutable one in Rust. It is the primitive behind 'Cell' and 'RefCell'. Using it directly is highly unsafe and requires the developer to manually guarantee that no other references exist simultaneously.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::cell::UnsafeCell;
 
struct MyCell<T> {
value: UnsafeCell<T>,
}
 
impl<T> MyCell<T> {
pub fn get_mut_unsafe(&self) -> &mut T {
unsafe { &mut *self.value.get() }
}
}
 
// Usage is dangerous and requires strict manual tracking of borrows.
Breakdown
1
self.value.get()
Returns a raw pointer (*mut T) to the wrapped value.
2
&mut *self.value.get()
Dereferences the raw pointer and casts it to a mutable reference.