当计数为 1 时,有条件地将 T 从 Rc<T> 中移出

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

有没有办法在计数为 1 时从 Rc<T> 移动对象?我正在考虑如何实施:

fn take_ownership<T>(shared: Rc<T>) -> Result<T, Rc<T>> { ... }

语义是,如果计数为 1,您会得到 T,否则您会返回 shared,这样您可以稍后再试。

标准库提供了Rc::try_unwrap函数:

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