Rust closure, RefCell, Rc Count

68 views Asked by At

counter_clone is in the closure. As a result, counter is not added and still remain 0 Would you mind if I ask you to fix this issue? Thank you!

/// 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
}
1

There are 1 answers

0
Masklinn On

You don't provide a Minimal Reproducible Example, and your snippet has multiple code hooks with unknowable behaviours (and possible bugs).

As usual select is not broken, RefCell and Rc certainly work fine, including with closures:

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

prints

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

as one would expect.

I would assume your n and result_func are where the issue lies, and the closure is never invoked. That is by far the most likely explanation. But since you don't provide either and SO has yet to deliver the pyschic remote mind reader I asked for, that's as far as I can assist.