borrow_mut() on my RefCell-like structure doesn't work
我尝试编写自己的类似于
失败的代码:
1 2 3 4 5 6 7 8 | let real_refcell= Rc::from(RefCell::from(MyStruct::new())); let nooverhead_refcell = Rc::from(NORefCell::from(MyStruct::new())); // works let refmut_refcell = real_refcell.borrow_mut(); // cannot borrow as mutable let refmut_norefcell = nooverhead_refcell.borrow_mut(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | use crate::norc_ref::{NORefMut, NORef}; use std::cell::UnsafeCell; use std::borrow::Borrow; #[derive(Debug)] pub struct NORefCell<T: ?Sized> { value: UnsafeCell< T > } impl< T > NORefCell< T > { pub fn from(t: T) -> NORefCell< T > { NORefCell { value: UnsafeCell::from(t) } } pub fn borrow(&self) -> NORef<'_, T> { NORef { value: unsafe { &*self.value.get() } } } pub fn borrow_mut(&mut self) -> NORefMut<'_, T> { NORefMut { value: unsafe { &mut *self.value.get() } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | use std::ops::{Deref, DerefMut}; #[derive(Debug)] pub struct NORef<'b, T: ?Sized + 'b> { pub value: &'b T, } impl<T: ?Sized> Deref for NORef<'_, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } /// No Overhead Ref Cell: Mutable Reference #[derive(Debug)] pub struct NORefMut<'b, T: ?Sized + 'b> { pub value: &'b mut T, } impl<T: ?Sized> Deref for NORefMut<'_, T> { type Target = T; #[inline] fn deref(&self) -> &T { self.value } } impl<T: ?Sized> DerefMut for NORefMut<'_, T> { #[inline] fn deref_mut(&mut self) -> &mut T { self.value } } |
如我的评论中所述:您基本上在做什么是围绕
The compiler makes optimizations based on the knowledge that &T is not mutably aliased or mutated, and that &mut T is unique. UnsafeCell is the only core language feature to work around the restriction that &T may not be mutated.
您正在为这个强大的对象提供一个瘦包装器,在API边界上没有