~icefox/garnet#69: 
Actually figure out closures

From #65:

...do all closures take their environment by reference like Rust, or do they move it by default (what I was implicitly assuming here, since everything is Copy in the current implementation, including From). I haven't thought about this too hard yet, I've just been saying "we'll do it like C++ even if it feels wrong, and have the ability to specify what the environment of a closure is and how it borrows the things in it" and brushing off details for later.

Then someone instantly pointed me at https://www.youtube.com/watch?v=EqiLTgQcDPM (Lightning Talk: Let's Write a Lambda in C++ - Ben Deane) which is absolute gold and also terrifying. So I should probably put some actual thought into this.

I want to depart from the bog-standard "do what Rust does" in a few ways:

  • In Rust, the Fn() family of traits are kinda magical, you can't just implement them yourself.
  • In Rust, type and lifetime(?) inference work somewhat differently inside and outside of closures.
  • In fact, functions/function pointers and closures in Rust are almost entirely separate things, which Feels Bad. Surely, a function is just a closure with an empty environment, right? Well you can't really use it that way, no.
  • In Rust, returning a closure is Weirdly Difficult, and implementing dynamic dispatch by having an if statement that returns one of a few different closures is impossible without boxing them, even if all the closures share the same environment. I'm used to this now and just program around it, but it was real annoying for my OCaml-coded brain to figure out when I was learning Rust.
  • We're probably going to spend a lot of time in Garnet implementing interfaces by stuffing closures or functions into structs,

Basically, IMO closures in Rust are over-specialized for sticking them into quick little iterator chains, which leaves lots of other interesting use cases underserved. I don't know how easy or possible it is to fix this, but I'd rather like to try.

Status
REPORTED
Submitter
~icefox
Assigned to
No-one
Submitted
7 months ago
Updated
7 months ago
Labels
T-DESIGN