Can two iterators into the same string be converted into a slice?

Is it possible for us to convert two iterators (to the same string) into an equivalent slice? Is there a method which will take these two iterators and return a slice representing the equivalent string span (contained between the iterators).

Can you explain a bit more, perhaps with some code? It's not clear exactly what you're asking.

A Rust Iterator is not quite like the C++ iterators you may be used to, which are little more than pointers. In Rust, the iterator already knows its beginning and end. This is also what enables DoubleEndedIterator, so you can even pull from the back.

You may like slice::Iter::as_slice(), slice::IterMut::into_slice(), and str::Chars::as_str(), which all turn the remainder of an iterator back into an appropriate slice.

1 Like

I hope the following code is able to explain what I want ...

fn main() {
    let s = "012345";
    let i1 = s.chars().skip(2);
    let i2 = s.chars().skip(4);
    assert_eq!(to_slice(i1, i2), "23");

Edit: fixed off by one error.

This is almost what I want but not quite there. Take a look at this post to see what I mean.

Uh, shouldn't that be "23"?

No, there's no way to do this with iterators; there isn't even any way to do it with slices. The simplest way is probably to copy+paste this trait and its implementation, then use it to define a new method that does "between slicing".

Yes it probably should be :smiley:

Your trait implementation looks promising! The as_ptr() method is new to me. Let me see if I can create an implementation of to_slice as described in the code snippet I posted.