简体   繁体   中英

How can I return a function?

I tried recreate functional composition

fn compose<A, B, C>(f : |B| -> C,
                    g : |A| -> B)
                    ->  |A| -> C{
  |x| f(g(x))
}

But I get a lifetime error. I read that closures are stack based but it doesn't explain why I get this error.

let f3 = compose(f1,f2);

Can't I move the closure out of it's current scope?

Yes, Rust's current closures capture by reference, and place the closure's environment (ie the references to the captured variables) on the stack, referring to it via a reference. Hence, any time you have a closure that captures outer variables (you are capturing f and g ), it is chained to the stack frame in which it was created.

C++11-style unboxed closures solve this, by allowing values to be captured by value, and allowing the environment to be stored directly (ie no compulsory references). The exact syntax is yet to be finalised, but what you wrote may be valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM