Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The code for

The code for Interior Mutability in Rust: Understanding The Cell Type

Today we are going to be talking about smart pointers and interior mutability, specifically, the Cell type. Cell is a type that you come across frequently in Rust programs that it can help to have a deeper understanding of what it is and how it works. One of the best ways to understand Cell and the fundemental concepts behind its implementation is to actually write it yourself. So that is what we are going to do!

use std::cell::UnsafeCell;
pub struct Cell<T> {
value: UnsafeCell<T>
}
// implied by UnsafeCell
// impl<T> !Sync for Cell<T> {}
impl<T> Cell<T> {
pub fn new(value: T) -> Self {
Cell { value: UnsafeCell::new(value) }
}
pub fn set(&self, value: T) {
// SAFETY: We know that no-one else is mutating self.value (because Cell is !Sync)
// and we know that we are not invalidating any references because we never give any out
unsafe { *self.value.get() = value };
}
pub fn get(&self) -> T
where
T: Copy,
{
// SAFETY: We know that no-one else is mutating self.value (because Cell is !Sync)
unsafe { *self.value.get() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment