Conditionally move T out from Rc when the count

2019-05-26 08:56发布

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条回答
smile是对你的礼貌
2楼-- · 2019-05-26 09:37

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);
查看更多
登录 后发表回答