Evian
Evian

Reputation: 1207

Rust -- How to call and pass a closure in an iteration?

I have an iteration:

fn foo<F>(mut callback: F)
    where F: FnMut(MyStruct)
{
    // produce an instance of MyStruct
    callback(my_struct);
    for ... { // some conditions
        foo(callback)
    }
}

And the closure may be:

let my_vec = vec![];
let mut callback = |my_struct: MyStruct| {my_vec.push(my_struct);};
foo(callback);

In my for loop, the ownership of callback is moved, so the code above doesn't work. I try to replace the parameter to mut callback: &mut F, and use foo(&mut callback), which still doesn't work, and the compiler says "overflow evaluating the requirement".

Upvotes: 0

Views: 567

Answers (1)

Jmb
Jmb

Reputation: 23453

Remove the &mut when recursing:

fn foo<F>(callback: &mut F)
    where F: FnMut(MyStruct)
{
    let my_struct = MyStruct;
    callback(my_struct);
    for _ in 0..3 { // some conditions
        foo(callback);      // <- HERE
    }
}

Playground (note: this overflows the stack when run due to the infinite recursion of foo. I assume that your real code uses a loop condition that causes the recursion to terminate…)

Upvotes: 1

Related Questions