有条件地将T从Rc T 移出当计数为 1 [英] Conditionally move T out from Rc<T> when the count is 1

查看:42
本文介绍了有条件地将T从Rc T 移出当计数为 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

fn take_ownership(共享:Rc)->结果 T,Rc T .{ ... }

语义是,如果计数为 1,您将获得 T,否则您将返回 shared,以便您稍后再试.

解决方案

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

<块引用>

fn try_unwrap(this: Rc) ->结果 T,Rc T .

返回包含的值,如果 Rc 正好有一个强参考.

否则,将返回一个 Err 与传入的相同 Rc.

即使存在突出的弱引用,这也会成功.

示例

使用 std::rc::Rc;让 x = Rc::new(3);assert_eq!(Rc::try_unwrap(x), Ok(3));让 x = Rc::new(4);让 _y = Rc::clone(&x);assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);

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.

解决方案

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

这篇关于有条件地将T从Rc T 移出当计数为 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆