[rust-dev] Closure types and iterators: impossible constraints?

Abraham Egnor abe.egnor at gmail.com
Sun Jan 19 08:09:06 PST 2014


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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140119/dea608e4/attachment-0001.html>


More information about the Rust-dev mailing list