rust工厂怎么刷卡_[大海啊 你全是水]Rust Iter

水文笔记警告⚠️ 勿看 包含大量个人用语和不成熟理解

Iter是平常用的最多了, 没事瞅瞅

迭代器模式

才了解到迭代器是一种设计模式(design pattern) ,我太菜了

遍历集合中的元素而不暴露底层实现,这里又涉及到内部迭代器和外部迭代器

自定义一个简单内部迭代器,内部迭代器传入元素和操作闭包之后就无法再进行操作,必须等遍历完才能够停下,中间没办法对迭代器进行操作

traitInIterator{fn each T>(&mutself,f: F);}implInIteratorforVec{fn each T>(&mutself,f: F){letmuti=0;whilei

现在为了更灵活,采用外部迭代器.自己自定义实现了一个外部迭代器

traitIterator{fn next(&mutself)-> Option;fn current(&self)-> Option;fn has_next(&self)-> bool;fn reset(&mutself);}struct Container{data: Vec,}struct ContaineIterator{idx: usize,container: &'aContainer,}implContaineIterator{fn new(container: &'aContainer)-> ContaineIterator{ContaineIterator{idx: 0,container}}}implIteratorforContaineIterator{fn next(&mutself)-> Option{letitem=self.container.data.get(self.idx).cloned();self.idx+=1;item}fn current(&self)-> Option{self.container.data.get(self.idx).cloned()}fn has_next(&self)-> bool {self.container.data.len()>self.idx}fn reset(&mutself){self.idx=0;}}implContainer{fn new()-> Container{Container{data: Vec::new()}}fn add_item(&mutself,item: T){self.data.push(item);}fn iter(&self)-> implIterator+'_{ContaineIterator::new(self)}}fn main(){letmutc=Container::new();c.add_item(1);c.add_item(2);c.add_item(3);letmutiter=c.iter();lethas_next=iter.has_next();assert_eq!(has_next,true);letitem=iter.next();println!("{:?}",item);iter.reset();whileiter.has_next(){letv=iter.next().unwrap();println!("item {:?}",v);}letitem=iter.next();assert_eq!(item,None)unwarp;letitem=iter.next();assert_eq!(item,None);}

for 循环也是个外部迭代器的语法糖

fn main(){letv=vec![1,2,3];foriinv{println!("{}",i);}letv=vec![1,2,3];{letmutiter=v.into_iter();loop{matchiter.next(){Some(i)=>{println!("{}",i);}None=>break,}}}}

Iterator Trait

可以看到将Iter结构说的很清楚了,通过上面自己实现的迭代器This module is largely organized by type:Traits are the core portion: these traits define what kind of iterators exist and what you can do with them. The methods of these traits are worth putting some extra study time into.

Functions provide some helpful ways to create some basic iterators.

Structs are often the return types of the various methods on this module's traits. You'll usually want to look at the method that creates the struct, rather than the struct itself. For more detail about why, see 'Implementing Iterator'.

用Iterator trait 定义方法

pubtraitIterator{type Item;fn next(&mutself)-> Option<:item>;fn size_hint(&self)-> (usize,Option){...}fn count(self)-> usize {...}fn last(self)-> Option<:item>{...}fn nth(&mutself,n: usize)-> Option<:item>{...}fn step_by(self,step: usize)-> StepBy{...}fn chain(self,other: U)-> Chain::IntoIter>///.......///.......TODO

这有有点问题是关于迭代器中上界和下界的理解,数组上界和下界一样,默认迭代器长度和无限迭代器

还有reserve的理解有点没明白

IntoIterator Trait

接下来就是转换成迭代器

pubtraitIntoIteratorwhere<:intoiterasiterator>::Item==Self::Item,{type Item;type IntoIter: Iterator;fn into_iter(self)-> Self::IntoIter;}

不同类型转换为Iter定一个不同的IntoIter结构体 并且被Iterator Trait 绑定,拥有next等方法

例如 Vec距离, 具体如下图

implIntoIteratorforVecimplIntoIteratorfor&'aVecimplIntoIteratorfor&'amutVec

从上面看有三种不同的迭代器· IntoIter,转移所有权,对应self。

· Iter,获得不可变借用,对应&self。

· IterMut,获得可变借用,对应&mut self。

底下是关于数组源码中定义在impl [T]中的方法,可以看到都有统一的行为

pubstruct Iter{ptr: NonNull,end: *constT,// If T is a ZST, this is actually ptr+len. This encoding is picked so that// ptr == end is a quick test for the Iterator being empty, that works// for both ZST and non-ZST._marker: marker::PhantomData,}pubfn iter(&self)-> Iter{unsafe{letptr=self.as_ptr();assume(!ptr.is_null());letend=ifmem::size_of::()==0{(ptras*constu8).wrapping_add(self.len())as*constT}else{ptr.add(self.len())};Iter{ptr: NonNull::new_unchecked(ptras*mutT),end,_marker: marker::PhantomData}}}//collect::IntoIterator for &[T; _]implIntoIteratorfor&'a[T;N]where[T;N]: LengthAtMost32,{type Item=&'aT;type IntoIter=Iter;fn into_iter(self)-> Iter{self.iter()}}

迭代器适配器

可以看到还有一堆 Struct 没讲,大部分都是适配器

#[must_use = "iterators are lazy and do nothing unless consumed"]表明适配器是惰性的如果没有对迭代器产生任 何“消费”行为,它是不会发生真正的迭代的

#[must_use ="iterators are lazy and do nothing unless consumed"]#[stable(feature ="rust1", since ="1.0.0")]#[derive(Clone)]pubstruct Filter{iter: I,predicate: P,}implFilter{pub(super)fn new(iter: I,predicate: P)-> Filter{Filter{iter,predicate}}}

​ 实现也很简单,相当于传入迭代器和一个方法(闭包),表明拥有的行为,为啥是惰性的.可以理解为你虽然有这个方法,但是你得去调用才能去执行.

消费器

去使用迭代器里面的方法叫做消费器,比如 next()就是消费器,遍历迭代器里的元素.实现没啥难的= =

等以后有啥不明白的再回来补吧 (摸了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值