zabolekar
zabolekar

Reputation: 1644

Function that captures a copy of the loop counter in Rust

I have some C++ code that looks like this (simplified to the point of being useless, but I hope you get the idea). It fills a vector of functions in a loop and makes every function capture the loop counter by copy:

std::vector<std::function<int()>> v;
for(int i = 1; i < N; i++) {
   v.push_back([i]() {return i;});
}

for(auto f: v) {
   std::cout << f() << "\n";
}

I'm looking for the Rust equivalent of this. Currently, I have the following idea:

let mut v: Vec<Box<Fn() -> i32>> = vec![];
for i in 1..6 {
   v.push((|i| {Box::new(move || i)})(i));
}

for f in v {
   println!("{}", f());
}

It works correctly, but I'm not sure whether it is the preferred way. Is calling a helper function really needed to achieve this or is there a more idiomatic way?

Upvotes: 3

Views: 150

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477434

How about just:

v.push(Box::new(move || i));

A complete demo:

fn main() {
    let mut v: Vec<Box<Fn() -> i32>> = vec![];
    for i in 1..6 {
        v.push(Box::new(move || i));
    }

    for f in v {
        println!("{}", f());
    }
}

Upvotes: 4

Related Questions