rust - Borrowing from Weak<T> -
i feel rc::weak
use (sort of) asref
trait implementation. i'm trying borrow shared content weak pointer, won't compile:
use std::rc::weak; struct thing<t>(weak<t>); impl<t> thing<t> { fn as_ref(&self) -> option<&t> { self.0.upgrade().map(|rc| { rc.as_ref() }) } // clarity, without confusing closure fn unwrapped_as_ref(&self) -> &t { self.0.upgrade().unwrap().as_ref() } }
i understand why: upgraded rc
not survive as_ref
call. seems me sound. possible magic trick using unsafe
compile:
impl<t> thing<t> { fn unwrapped_as_ref<'a>(&'a self) -> &'a t { let rc = self.0.upgrade().unwrap(); unsafe { std::mem::transmute(rc.as_ref()) } } }
so:
- are there downsides solution? sound? can think of simpler alternative?
- would make sense implement
as_ref(&self) -> option<&t>
in standard library?
you can’t borrow weak reference, can’t. it’s weak, not guarantee underlying object exists (that’s why upgrade()
returns option
). , if lucky , value still alive @ point accessed through weak reference (upgrade()
returned some
), can freed next moment, upgrade
d reference goes out of scope.
in order reference underlying value need something keep alive (e.g. strong reference), means you’ll have return along reference.
Comments
Post a Comment