Search code examples
arraysstringrustsplitdestructive-read

How do I desctructively iterate over an array of strings in rust?


MRE:

let mut ws = s.split_whitespace();
for w in ws {
    if w == "option1" { //do something }
    else if w == "option2" { //do something else }...
    // this is the tricky part
    else if w == "{" { // call the function recursively to process the inner set of 'w's but pass it 's' because the for loop destroys s as it reads through it }
}

Is there a way to achieve this is rust? I am assuming I would have to use a more complex for loop than a simple "foreach iterative loop" and would have to do something on the lines of: for i in 0..len(ws) and then somehow dynamically change ws so its length changes?


Solution

  • Are you looking for something like this

    fn handle_token<'a>(tokens: &mut impl Iterator<Item = &'a str>) {
        while let Some(t) = tokens.next() {
            match t {
                "foo" => println!("foo"),
                "bar" => println!("bar"),
                "{" => {
                    println!(">> enter");
                    handle_token(tokens);
                    println!("<< exit");
                },
                "}" => {
                    break;
                }
                _=> unimplemented!()
            }
        }
    }
    
    fn main() {
        let mut ws = "foo bar { foo bar } bar".split_whitespace();
        handle_token(&mut ws);
    }
    
    foo
    bar
    >> enter
    foo
    bar
    << exit
    bar