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

admin2025-04-21  0

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?

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?

Share Improve this question edited Feb 3 at 3:13 kesarling asked Feb 3 at 3:00 kesarlingkesarling 2,2804 gold badges18 silver badges49 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745251074a292509.html

最新回复(0)