如何将正在迭代的迭代器传递给函数?

How do I pass an iterator I am iterating on to a function?

我正在遍历一个数组,根据当前值,我想将迭代器传递给子函数并让它处理多个值,并在退出子函数时进行遍历数组。下面是我到目前为止最接近的,但我一直在 error: use of moved value: 'iter'.

我试过研究生命周期,但这对我也没有用。我现在大部分时间都花在这上面,但似乎无济于事。任何帮助将不胜感激。谢谢

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 构造使用迭代器,使用它做您想做的事情将非常棘手(如果不是不可能的话,我真的不确定)。

但是,您可以通过切换到 while let 构造来轻松地使其工作,如下所示:

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)),
            _ => {},
        }
    }
}