-->

Conditionally move T out from Rc when the count

2019-05-26 09:44发布

问题:

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 same Rc 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);