Add as_str method for str::Split(Whitespace)

985dfeb
Opened by crumblingstatue at 2020-10-23 07:18:23

Consider the following use case:

// A command interpreter with a "print" command, which prints what comes after it
let mut words = line.split_whitespace();

match words.next() {
    "print" => {
        // How could we get the rest that comes after the command word?
        // We could perhaps collect the words, and join them with a space, but that's lossy,
        // and doesn't sound very efficient.
        let rest;
        println!("{}", rest),
    }
    unk => println!("Unknown command: {}", unk),
}

Some iterators, like str::Chars already have an as_str method. The only question is whether it is possible to implement as_str for the Split API, without making any breaking changes.

  1. https://github.com/rust-lang/rust/pull/34204 has a previous attempt and some discussion

    Oli Scherer at 2017-07-06 19:52:12

  2. Meanwhile, I implemented an alternative SplitWhitespace, because I frequently make use of this feature.

    crumblingstatue at 2017-07-09 09:52:36

  3. I would be open to adding this for str's split iterators, as long as it does not require all Searchers to support as_str which isn't possible because of https://github.com/rust-lang/rust/pull/34204#issuecomment-228875391.

    David Tolnay at 2017-11-18 19:29:39

  4. Do I understand correctly that it's impossible just for reverse iterator? In other words, implementing this for forward iterator should be fine, right?

    If yes, then maybe we could implement just that, as I expect that case to be most common, so it's already useful. I'm willing to do PR.

    Martin Habovštiak at 2020-02-14 15:59:36

  5. Split now has it thanks to #75265, but SplitWhitespace still doesn't, so I'm not closing this issue yet.

    crumblingstatue at 2020-10-23 07:18:11