2

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?

1 Answer 1

4

Yes, Rust's current closures capture by reference, and place the closure's environment (i.e. 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 (i.e. no compulsory references). The exact syntax is yet to be finalised, but what you wrote may be valid.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.