如何将要迭代的迭代器传递给函数? [英] How do I pass an iterator I am iterating on to a function?

查看:130
本文介绍了如何将要迭代的迭代器传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历数组,并根据当前值,我想将迭代器传递给子函数,并使其处理多个值,并在退出子函数时进行迭代通过数组.以下是我到目前为止可以找到的最接近的结果,但是我一直得到error: use of moved value: 'iter'.

I'm iterating through an array, and depending on the current value, I'd like to pass the iterator to a sub function and have it deal with a number of values, and upon exiting the sub function, carry on iterating through the array. Below is the closest I've managed to get so far, but I keep getting error: use of moved value: 'iter'.

我已经尝试过研究一生,但这对我也没有用.我现在已经花了整整一天的时间,似乎无法解决任何问题.任何帮助将不胜感激.谢谢.

I've tried looking into lifetimes, but that hasn't worked for me either. I've spent most of a day on this now, and can't seem to get anywhere with it. Any help would be greatly appreciated. Thanks.

enum Thing {
    Three(char, char, char),
    Four(char, char, char, char),
}

fn take_three <'a>(iter: &mut std::slice::Iter<'a, char>) -> Thing {
    let a = iter.next().unwrap();
    let b = iter.next().unwrap();
    let c = iter.next().unwrap();
    Thing::Three(*a,*b,*c)
}

fn take_four <'a>(iter: &mut std::slice::Iter<'a, char>) -> Thing {
    let a = iter.next().unwrap();
    let b = iter.next().unwrap();
    let c = iter.next().unwrap();
    let d = iter.next().unwrap();
    Thing::Four(*a,*b,*c,*d)
}

fn parse_tokens (tokens: &Vec<char>) {
    let mut iter = tokens.iter();
    let mut things: Vec<Thing> = vec![];
    for token in iter {
        match token {
            &'a' => things.push(take_three(&mut iter)),
            &'b' => things.push(take_four(&mut iter)),
            _ => {},
        }
    }
}

fn main() {
    let tokens = vec!['a', '1', '2', '3', 'b', '1', '2', '3', '4', 'a', '4', '5', '6'];
    parse_tokens(&tokens);
}

推荐答案

for构造会消耗迭代器,并且使用它进行您想要的操作非常棘手(如果不是不可能的话,我真的不确定).

The for construct consumes the iterator, and doing what you want using it will be quite tricky (if not impossible, I'm really not sure about that).

但是,通过切换到while let构造,您可以使它很容易地工作,如下所示:

However, you can have it working pretty easily by switching to a while let construct, like this:

fn parse_tokens (tokens: &Vec<char>) {
    let mut iter = tokens.iter();
    let mut things: Vec<Thing> = vec![];
    while let Some(token) = iter.next() {
        match token {
            &'a' => things.push(take_three(&mut iter)),
            &'b' => things.push(take_four(&mut iter)),
            _ => {},
        }
    }
}

这篇关于如何将要迭代的迭代器传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆