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

MRE:let mut ws = s.split_whitespace();for w in ws {if w == "option1" { do something }else

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745251073a4618680.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信