Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How do you implement closures entirely on the stack? What about the case when a function returns a closure into an external translation unit? How do you cover the bound parameters? You can't do call-time lambda lifting if the bound parameters are out of scope at the call site, you need to put something on the heap and GC it. Same with compile-time lambda lifting (producing a chain of bind1st stubs on the executable heap)


My mistake. I meant to write "can SOMETIMES be entirely on the stack" -- fixed that just now.

Functions indeed cannot return closures without heap-allocating them. (It might be possible in specific obscure cases, but definitely not in general.) However, if you wish to curry a function foo(a,b), you can do that in the caller (instead of at the function definition itself) by writing:

let curried_foo = |b| foo(a,b);

That is then stack-allocated and can refer to 'a' in the same frame, and can be passed to other functions you might call from there (but not returned upwards, indeed).


I'm not an expert, but I believe that Rust will allocate closures depending on the data that they close over. So if you reference a stack-allocated variable from within your closure, it gets put on the stack. If you reference a heap-allocated variable from within your closure, it gets put on the heap.

I could be dreadfully wrong, though.


No, where a closure is allocated depends on the type of the closure. The type of the closure is inferred just like any other type. It has nothing to do with what it closes over (although what it the closure is allowed to close over depends on its type).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: