[rust-dev] returning functions in rust

Patrick Walton pcwalton at mozilla.com
Fri Jan 10 10:18:36 PST 2014


On 1/10/14 7:20 AM, Nakamura wrote:
> I'm new to rust, and tried going through some of the examples from the
> OS class[0] that was taught in rust.  However, I got tripped up by the
> exercise, "make a function that takes an integer n and another function
> |x| -> x, and returns a function that is n applications of the original
> function."
>
> I've been trying to see what the limits of rust are if you are using it
> without the runtime/managed pointers etc, and it seems like I stumble
> against one of the limits when trying to return functions.  The big
> question is where to allocate the new function I want to return.

Rust won't automatically allocate closed-over variables on the heap. 
This limits the ability to write code like this naturally, but you get 
the benefit that all allocations are immediately visible and under the 
control of the programmer.

I would not suggest trying to use managed pointers for this. Instead I 
would suggest `proc`, which is allocated on the exchange heap and can 
close over variables. This should be sufficient for the question as 
posed, as long as the "another function" has a `'static` bound (`'static 
|x| -> x`).

Patrick



More information about the Rust-dev mailing list