← 中文资源

简体中文版本

Rc Try Unwrap 取回值

在还有其他句柄时调用 Rc::try_unwrap 会失败,先释放副本再取回内部的 String,无需克隆。

阅读英文原文

实现说明

Rc Try Unwrap 取回值可以归结为函数 main。 match 逐一列出值的可能形态,漏掉的分支编译器会拒绝。

使用要点

  • 每一步打印都带着自己的标签:strong count:、unexpected owner:、still shared:。

常见问题

运行「Rc Try Unwrap 取回值」会打印什么?

整个文件跑完,输出行以 strong count:、unexpected owner:、still shared: 这类前缀开头。

核心语句

match Rc::try_unwrap(extra) {
    Ok(value) => println!("unexpected owner: {value}"),
    Err(rc) => {
        println!("still shared: {}", Rc::strong_count(&rc));
        drop(rc);
    }
}
let value = Rc::try_unwrap(shared).unwrap_or_else(|_| String::from("failed"));

代码示例

use std::rc::Rc;

fn main() {
    let shared = Rc::new(String::from("payload"));
    let clone = Rc::clone(&shared);
    println!("strong count: {}", Rc::strong_count(&shared));

    // an extra handle makes try_unwrap fail instead of stealing the value
    let extra = Rc::clone(&shared);
    match Rc::try_unwrap(extra) {
        Ok(value) => println!("unexpected owner: {value}"),
        Err(rc) => {
            println!("still shared: {}", Rc::strong_count(&rc));
            drop(rc);
        }
    }

    // dropping the clone leaves exactly one owner
    drop(clone);
    println!("after drop: {}", Rc::strong_count(&shared));

    let value = Rc::try_unwrap(shared).unwrap_or_else(|_| String::from("failed"));
    println!("reclaimed: {value}");
}