pub struct Immutable<T>(/* private fields */);Expand description
A wrapper that provides read-only access to a value
This type is meant to prevent accidental modifications of values after construction. It can not however, prevent replacement of the value itself. For example:
use cut::Immutable;
let mut val = Immutable::new(10);
// later...
val = Immutable::new(11);
assert_eq!(*val, 11);use cut::Immutable;
struct Foo {
bar: Immutable<bool>,
}
impl Foo {
pub fn new(bar: bool) -> Self {
Self {
bar: Immutable::new(bar),
}
}
pub fn bar(&mut self) -> bool {
// ERROR
//self.bar = !*self.bar;
// if From<T> was implemented for Immutable<T>, you might accidently do this:
//self.bar = (!*self.bar).into();
// uh oh...
// atleast you can explictly see that a new Immutable<T> is being assigned
self.bar = Immutable::new(!*self.bar);
*self.bar
}
}
let mut foo = Foo::new(false);
assert_eq!(foo.bar(), true);
assert_eq!(foo.bar(), false);
assert_eq!(foo.bar(), true);Types with interior mutability such as Cell can still be modified when
wrapped. This includes nesting such as the following:
use core::cell::Cell;
use cut::Immutable;
struct Foo {
bar: Bar,
}
struct Bar {
baz: Cell<bool>,
}
let foo = Immutable::new(Foo {
bar: Bar {
baz: Cell::new(false),
},
});
foo.bar.baz.set(true);
assert_eq!(foo.bar.baz.get(), true);Implementations§
Trait Implementations§
impl<T: Copy> Copy for Immutable<T>
impl<T: Eq> Eq for Immutable<T>
Source§impl<T: Ord> Ord for Immutable<T>
impl<T: Ord> Ord for Immutable<T>
1.21.0 (const: unstable) · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§fn min(self, other: Self) -> Selfwhere
Self: Sized,
fn min(self, other: Self) -> Selfwhere
Self: Sized,
Compares and returns the minimum of two values. Read more
Source§impl<T: PartialOrd> PartialOrd for Immutable<T>
impl<T: PartialOrd> PartialOrd for Immutable<T>
impl<T: PartialEq> StructuralPartialEq for Immutable<T>
Auto Trait Implementations§
impl<T> Freeze for Immutable<T>where
T: Freeze,
impl<T> RefUnwindSafe for Immutable<T>where
T: RefUnwindSafe,
impl<T> Send for Immutable<T>where
T: Send,
impl<T> Sync for Immutable<T>where
T: Sync,
impl<T> Unpin for Immutable<T>where
T: Unpin,
impl<T> UnsafeUnpin for Immutable<T>where
T: UnsafeUnpin,
impl<T> UnwindSafe for Immutable<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more