2017-12-05 13 views
2

[1,2,2,3,4,4][2,4]을 생성해야합니다. 다음 번호가 같은 번호 만 찾아야합니다. 다음 번호를 들여다보아야하므로 Peekable iterator을 사용해 보았습니다. filter을 작성했습니다.필터 클로저에서 Peekable 반복기는 어떻게 사용합니까?

fn main() { 
    let xs = [1, 2, 2, 3, 4, 4]; 
    let mut iter = xs.iter().peekable(); 

    let pairs = iter.filter(move |num| { 
     match iter.peek() { 
      Some(next) => num == next, 
      None  => false, 
     } 
    }); 

    for num in pairs { 
     println!("{}", num); 
    } 
} 

나는 오류 얻을 :

error[E0382]: capture of moved value: `iter` 
--> src/main.rs:6:15 
    | 
5 |  let pairs = iter.filter(move |num| { 
    |     ---- value moved here 
6 |   match iter.peek() { 
    |    ^^^^ value captured here after move 
    | 
    = note: move occurs because `iter` has type `std::iter::Peekable<std::slice::Iter<'_, i32>>`, which does not implement the `Copy` trait 

내가 iter가 폐쇄 사용하고 있기 때문에이 생각을하지만, 그것을 빌려 않았으며, 그것을 복사 할 수 없습니다.

필터 내부의 반복기를 참조하려는이 문제를 어떻게 해결할 수 있습니까?

답변

3

refer to the iterator inside a filter

나는 그렇게 할 수 없다고 생각합니다. 당신이 그렇게되면,이

fn filter<P>(self, predicate: P) -> Filter<Self, P> 
where 
    P: FnMut(&Self::Item) -> bool, 

을 사라 : 당신이 filter를 호출 할 때, 그것은 기본 반복자의 소유권을 가져옵니다. 더 이상 iter이 없습니다. 유사한 경우에는 Iterator::by_ref을 사용하여 이터레이터를 변경 가능하게 빌려 잠시 동안 구동 한 다음 원본을 다시 참조 할 수 있습니다. 이 경우에는 내부 반복자가 두 번째로 가변적으로 빌릴 필요가 있으므로이 경우에는 작동하지 않습니다. 이는 허용되지 않습니다.

find only the numbers where the next number is the same.

extern crate itertools; 

use itertools::Itertools; 

fn main() { 
    let input = [1, 2, 2, 3, 4, 4]; 

    let pairs = input 
     .iter() 
     .tuple_windows() 
     .filter_map(|(a, b)| if a == b { Some(a) } else { None }); 

    let result: Vec<_> = pairs.cloned().collect(); 
    assert_eq!(result, [2, 4]); 
} 

또는 당신은 단지 표준 라이브러리 사용하여 뭔가를 원한다면 : 조각의 특정 경우

fn main() { 
    let xs = [1, 2, 2, 3, 4, 4]; 

    let mut prev = None; 
    let pairs = xs.iter().filter_map(move |curr| { 
     let next = if prev == Some(curr) { Some(curr) } else { None }; 
     prev = Some(curr); 
     next 
    }); 

    let result: Vec<_> = pairs.cloned().collect(); 
    assert_eq!(result, [2, 4]); 
} 
+2

, ['.windows()'(https : //로 문서를. rust-lang.org/std/slice/struct.Windows.html)은 Sublice를 Window로 생성하는데, Generic은 아니지만'tuple_windows'와 상대적으로 비슷합니다. –