use std::fmt::Debug; #[derive(Debug)] struct MyData<T:Clone>{ data: Vec<T> } impl<T:Clone+Debug> MyData<T> { fn group_by<F>(&self, pred: F)->MyGroupBy<T, F> where F: FnMut(&T,&T) ->bool { MyGroupBy { data: self.data.clone(), predicate: pred } } } struct MyGroupBy<T:Debug, P>{ data: Vec<T>, predicate: P } impl<T:Clone+Debug, P> Iterator for MyGroupBy<T, P> where P: FnMut(&T, &T) -> bool { type Item = Vec<T>; fn next(&mut self) -> Option<Self::Item> { if self.data.is_empty(){ None }else{ let mut len = 1; let mut iter = self.data.windows(2); while let Some([l,r]) = iter.next(){ if (self.predicate)(l, r) { len += 1 } else { break } } let tmp = self.data.clone(); let (head, tail) = tmp.split_at(len); self.data = tail.to_vec(); Some(head.to_vec()) } } } impl<T:Debug, P> std::fmt::Debug for MyGroupBy<T, P> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("GroupBy").field("slice", &self.data).finish() } } fn main () { let xx = vec![vec![1,2,3], vec![1,2,5], vec![2,3,5], vec![2,3,1]]; let myd = MyData{ data:xx }; let mut it = myd.group_by(|a, b|a[0]==b[0]).collect::<Vec<Vec<Vec<i32>>>>(); println!("{:?}", it); // for i in it{ // println!("{:?}", i); // } }
标签:mut,group,self,let,vec,data,MyGroupBy,rust From: https://www.cnblogs.com/pythonClub/p/16588978.html