How to assign to the variable used in match expression inside a match branch?

前端 未结 2 392
再見小時候
再見小時候 2021-01-27 04:25

I\'m trying to implement a general function join() that can work on any iterator of iterators. I have a problem with the borrow checker in a match expr

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-27 05:32

    In these kind of situations, I find useful to write the code in two pieces: first collect the data, then update the mutable:

    fn next(&mut self) -> Option {
        loop {
            //collect the change into a local variable
            let ii = match &mut self.inner_iter {
                Some(ref mut it) => {
                    match it.next() {
                        Some(x) => { return Some(x); }
                        None => self.outer_iter.next().map(|it| it.into_iter())
                    }
                }
                None => { return None; }
            };
            //self.inner_iter is no longer borrowed, update
            self.inner_iter = ii;
        }
    }
    

    The fact that all the branches that do not modify the inner_iter do a return makes the code easier.

提交回复
热议问题