pub struct TakeStatic<T: ?Sized> { /* private fields */ }Expand description
A synchronization primitive which can be accessed only once.
This type is a thread-safe cell that can only be used in statics.
TakeStatic::take provides a mutable reference to the contents without RAII guards, but only on the first try.
§Similarities with takecell::TakeCell
TakeStatic is similar to takecell::TakeCell in that both can be used to create singletons.
Additionally, TakeCells can be created at runtime, making them suitable for other use-cases such as doing work only once.
TakeStatic, on the other hand, is specialized to creating statics through take_static, allowing even !Send types to be used and not requiring explicitly naming the wrapper type.
§Similarities with cortex_m::singleton
TakeStatic can be used similarly to cortex_m::singleton to create a mutable reference to a statically allocated value.
In contrast to cortex_m::singleton, TakeStatic is thread safe.
§Examples
use take_static::take_static;
take_static! {
static NUMBER: usize = 5;
}
assert_eq!(NUMBER.take(), Some(&mut 5));
assert_eq!(NUMBER.take(), None);Implementations§
Source§impl<T: ?Sized> TakeStatic<T>
impl<T: ?Sized> TakeStatic<T>
Sourcepub fn take(&self) -> Option<&mut T>
pub fn take(&self) -> Option<&mut T>
Takes the mutable reference to the wrapped value.
Only the first call returns Some.
All subsequent calls return None.
§Examples
use take_static::take_static;
take_static! {
static TAKE_STATIC: usize = 5;
}
let number = TAKE_STATIC.take().unwrap();
assert_eq!(number, &mut 5);
assert!(TAKE_STATIC.take().is_none());