Losing std::str::Chars::as_str

Am I missing something?

The method std::str::Chars::as_str gives you an &str slice of the remainder of the string you're iterating over, which is useful. But many of the iterator methods, e.g., skip_while and especially peekable, return an interator adaptor, e.g., Peekable<Chars>, that does NOT support as_str.

Is there a way to get as_str back in these cases? I've been looking and I've not found one. In particular, I want to be able to use as_str with Peekable<Chars>.

Note: I'm not looking for complex work-arounds here; I can look at character lengths and wrangle slice indices if I have to. What I want to know is whether or not there's a simple efficient solution in the existing API that I'm missing.

You are not missing anything. There's no simple way for methods of specific iterators (like Chars::as_str) to work on iterator adaptors, sorry.


You can sorta kinda do it in some cases. But it won't work for the particular case of Peekable that you're interested in.

Basically, the idea is to use &mut Chars (using e.g. by_ref(), or even just &mut iter) so that you can keep the Chars.

fn main() {
    let s = "abacadaeafagah";
    // read up to (and including) the 4th 'a'
    let mut chars = s.chars();
    chars.by_ref().filter(|&c| c == 'a').take(4).for_each(|_| {});
    // now you can still use the chars to get the remainder
    assert_eq!(chars.as_str(), "eafagah");

As I said, this won't do work the way you'd want it to for something like Peekable, because Peekable will have read an extra item from the Chars if you called peek.


I don't see what is wrong with indexing; this is how I use it:

1 Like

Everything's wrong when you don't know that it exists. CharIndices is exactly what I'm looking for.

It is a problem with the Rust documentation that I've noticed before. There are so many useful things like s.char_indices that are not useful in my precise circumstances that the ones that might be go unnoticed. Or, too often, I might see one but it isn't obvious that whatever it is is exactly what I need.

Many, many thanks!