pub struct MutOnce<T> { /* private fields */ }
Expand description
A mutable memory location that is write-once and can be borrowed as
plain &T
.
Initially the value can be mutated through struct RefMut<T>
obtained by get_mut
method.
When there is no RefMut
alive, a shared reference &T
can be
taken by get_ref
method. Once get_ref
is called, get_mut
must
not be called again.
§Examples
use mutate_once::MutOnce;
struct Container {
expensive: MutOnce<String>,
}
impl Container {
fn expensive(&self) -> &str {
if !self.expensive.is_fixed() {
let mut ref_mut = self.expensive.get_mut();
*ref_mut += "expensive";
// Drop `ref_mut` before calling `get_ref`.
}
// A plain reference can be returned to the caller
// unlike `Cell` or `RefCell`.
self.expensive.get_ref()
}
}
let container = Container { expensive: MutOnce::new(String::new()) };
assert_eq!(container.expensive(), "expensive");
Implementations§
Source§impl<T> MutOnce<T>
impl<T> MutOnce<T>
Sourcepub fn get_mut(&self) -> RefMut<'_, T>
pub fn get_mut(&self) -> RefMut<'_, T>
Mutably borrows the wrapped value.
The borrow lasts until the returned RefMut
gets dropped.
This method must not be called if another RefMut
is active or
get_ref
is ever called.
§Panics
Panics if the value is currently mutably borrowed or ever immutably borrowed.
§Examples
let mo = mutate_once::MutOnce::new(0);
*mo.get_mut() += 2;
*mo.get_mut() += 5;
assert_eq!(*mo.get_ref(), 7);
Panics if another mutable borrow is active:
let mo = mutate_once::MutOnce::new(0);
let mut ref_mut = mo.get_mut();
*mo.get_mut() += 7; // Panics because `ref_mut` is still active.
Panics if get_ref
is ever called:
let mo = mutate_once::MutOnce::new(0);
assert_eq!(*mo.get_ref(), 0);
*mo.get_mut() += 7; // Panics because `get_ref` is called once.
Sourcepub fn get_ref(&self) -> &T
pub fn get_ref(&self) -> &T
Returns an immutable reference to the value.
This method must not be called while the value is mutably borrowed.
§Panics
Panics if the value is currently mutably borrowed.
§Examples
let mo = mutate_once::MutOnce::new(0);
*mo.get_mut() += 7;
assert_eq!(*mo.get_ref(), 7);
Panics if a mutable borrow is active:
let mo = mutate_once::MutOnce::new(0);
let mut ref_mut = mo.get_mut();
mo.get_ref(); // Panics because `ref_mut` is still active.
Sourcepub fn is_fixed(&self) -> bool
pub fn is_fixed(&self) -> bool
Returns true if the value can be no longer mutated (in other words,
if get_ref
is ever called).
Sourcepub fn into_inner(self) -> T
pub fn into_inner(self) -> T
Consumes the MutOnce
, returning the wrapped value.