On 10/27/13 5:15 AM, Ramakrishnan Muthukrishnan wrote:
I am having a hard time trying to figure out what is going on here.
fn ntimes(f: &fn(int) -> int, n: int) -> &fn(int) -> int {
match n {
0 => &|x| { x },
_ => &|x| { f(x) },
_ => &|x|
{
let nf = ntimes(f, n - 1);
nf(f(x))
},
}
}
The compiler is actually (admittedly obliquely) telling you about a
memory safety problem. Consider this line:
> _ => &|x| { f(x) },
Here you're referring to the outer variable (argument in this case) `f`.
But by the time the closure is invoked, `f` won't exist, because the
activation record for the `ntimes` function won't exist anymore. It's
the same problem that occurs when you return a pointer to an argument in
C. In Rust the lifetime system prevents such errors, and that's what
you're seeing.
Other languages get around this by moving `f` to a garbage collected box
implicitly, but that's contrary to the design of Rust, which has no GC
unless you explicitly opt in.
From the code snippet I'm not sure exactly what you're trying to do, so
I don't know the most idiomatic way to solve this.
Patrick
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev