I recently ran into an issue with closure types that seems to have no
solution present in the language.  In a silly example, say you want to
implement an iterator that wraps an int iterator and adds a value to it:

fn add_n<I: Iterator<Int>>(v: I, n: int) -> ???

This is naturally expressed as a map operation:

fn add_n<I: Iterator<Int>>(v: I, n: int) -> ??? {
  v.map(|i| i+n)
}

The problem here is that Iterator::map returns a value that is templated on
the lifetime of the closure passed in.  In other words, the result of
v.map(...) is only valid for the stack frame in which it's called; there's
no way to return it from the function.

It seems like it should be possible to resolve this problem by creating a
struct that owns the closure and can therefore also safely store the result
of the map() call, but I can't find a way to actually express this to the
compiler.

For this specific silly example it's trivial to directly implement the map
logic, but in the general case that means that you can't build new generic
iterator transformers on existing ones, which is a pretty terrible
situation.

Am I missing something or is this a hole in the language?
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to