gpt4 book ai didi

rust - 当计数为 1 时,有条件地将 T 从 Rc 移出

转载 作者:行者123 更新时间:2023-11-29 08:07:45 25 4
gpt4 key购买 nike

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

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

语义是你得到 T如果计数是 1然后你回来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);

关于rust - 当计数为 1 时,有条件地将 T 从 Rc<T> 移出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45530536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com