Rust 闭合、RefCell、Rc Count

问题描述 投票:0回答:1

counter_clone 在闭包中。 结果,counter没有被添加,仍然保持0 您介意我请您解决这个问题吗? 谢谢!

/// Implement a function to convert a Church numeral to a usize type.
pub fn to_usize<T: 'static + Default>(n: Church<T>) -> usize {
    use std::cell::RefCell;

    let counter = Rc::new(RefCell::new(0));
    let counter_clone = Rc::clone(&counter);

    let result_func = n(Rc::new(move |x| {
        *counter_clone.borrow_mut() += 1;
        x
    }));

    let _ = result_func(Default::default());

    // Extract the value from the reference-counted cell
    let result = *counter.borrow();

    result
}
rust closures refcell
1个回答
0
投票

您没有提供最小可重现示例,并且您的代码片段具有多个具有不可知行为(以及可能的错误)的代码挂钩。

RefCell
Rc
当然工作得很好:

use std::rc::Rc;
use std::cell::RefCell;

fn main() {
    let counter = Rc::new(RefCell::new(0));
    let counter_clone = Rc::clone(&counter);
    
    let f = move || *counter_clone.borrow_mut() += 1;

    dbg!(counter.borrow());
    f();
    dbg!(counter.borrow());
}

打印

[src/main.rs:10] counter.borrow() = 0
[src/main.rs:12] counter.borrow() = 1

正如人们所期望的那样。

© www.soinside.com 2019 - 2024. All rights reserved.