use std::ops::{Deref, DerefMut}; pub struct UnsafeRef { x: *const T, } impl Deref for UnsafeRef { type Target = T; fn deref(&self) -> &Self::Target { unsafe { return &*self.x; } } } impl UnsafeRef { pub fn new<'a>(x: &'a T) -> Self { return UnsafeRef { x }; } } pub struct UnsafeMutRef { x: *mut T, } impl Deref for UnsafeMutRef { type Target = T; fn deref(&self) -> &Self::Target { unsafe { return &*self.x; } } } impl DerefMut for UnsafeMutRef { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { return &mut *self.x; } } } impl UnsafeMutRef { pub fn new<'a>(x: &'a mut T) -> Self { return UnsafeMutRef { x }; } } #[cfg(test)] mod tests { use crate::{UnsafeMutRef, UnsafeRef}; trait Foo { fn set(&mut self, v: i32); fn get(&self) -> i32; } struct A(i32); impl Foo for A { fn set(&mut self, v: i32) { self.0 = v; } fn get(&self) -> i32 { self.0 } } #[test] fn it_works() { let mut a = A(0); let mut x: UnsafeMutRef = UnsafeMutRef::new(&mut a); let mut y: UnsafeMutRef = UnsafeMutRef::new(&mut a); let z: UnsafeRef = UnsafeRef::new(&a); x.set(42); y.set(z.get() + 10); if z.get() != 52 { panic!(); } } }