1

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?

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

I guess the way this works is that each time .next is called, tokens loses that element so that when the function is called on it again, it no longer has that element?
This is exactly what I needed! Could you help me understand why the lifetimes are needed? I'm still pretty new to rust.
That's just because split_whitespace return an iterator with Item = &str, and it just creep into the function. The Idea is that split_whitespace(&self) take &self as argument, that means that some other function might take ownership later on, and the compiler needs to make sure that you will not call something like to_string() which take ownership before you are done with the iterator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.