Conditionally move T out from Rc<T> when the count is 1

落花浮王杯 提交于 2019-12-08 02:04:31

问题


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


来源:https://stackoverflow.com/questions/45530536/conditionally-move-t-out-from-rct-when-the-count-is-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!