Editor's note: This question was asked before Rust 1.0 and some of the syntax has changed since then, but the underlying concepts remain. Some answers have been updated for Rust 1.0 syntax.
I'm new to Rust and trying to do something with closures which is trivial in JavaScript, Python, etc. but I am running into lifetime issues in Rust. I understand the error message, but it leads me to believe what I want to do is pretty hard in Rust.
I just want to create an array of functions, a
, such that
a[0]
is the function returning 0a[1]
is the function returning 1- ...
a[9]
is the function returning 9
I tried:
fn main() {
let a : [||->uint, ..10];
for i in range(0u, 10) {
a[i] = ||{i};
}
println!("{} {} {}", a[1](), a[5](), a[9]())
}
But I got a lifetime error. The reported error was "cannot infer an appropriate lifetime due to conflicting requirements" for the functions in a
because the lifetimes cannot outlive the while
block so that the closures cannot outlive their stack frame, which of course they would because I am invoking them in println!
.
I'm sure there must be a way to build up this array of functions, but how?
You need to use
move || i
.move
implies that this closure will takei
by value rather than by reference. By default, these closures would only take references toi
. In your case it is forbidden as the lifetime ofi
is limited to the body of the loop.Also, Rust will complain that your array may not be fully initialized. To avoid it, you can either use a
Vec<_>
, or usestd::mem::uninitialized
:It is possible to
collect
multiple closures from an iterator into aVec
:The
move
keyword causes ownership ofi
to be transferred to the closure.See also: