问题
Is there a way to move an object from an Rc<T>
when the count is 1
? I am thinking about how one would implement:
fn take_ownership<T>(shared: Rc<T>) -> Result<T, Rc<T>> { ... }
The semantics would be that you get T
if the count is 1
and you get back shared
otherwise so you can try again later.
回答1:
The standard library provides the Rc::try_unwrap function:
fn try_unwrap(this: Rc<T>) -> Result<T, Rc<T>>
Returns the contained value, if the
Rc
has exactly one strong reference.Otherwise, an
Err
is returned with the sameRc
that was passed in.This will succeed even if there are outstanding weak references.
Examples
use std::rc::Rc; let x = Rc::new(3); assert_eq!(Rc::try_unwrap(x), Ok(3)); let x = Rc::new(4); let _y = Rc::clone(&x); assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
来源:https://stackoverflow.com/questions/45530536/conditionally-move-t-out-from-rct-when-the-count-is-1