当前位置: 首页 > news >正文

Rust自定义迭代器

Rust自定义迭代器

Rust要自定迭代器要实现Iterator这个Trait,就可以使用next方法,也可以实现IntoIterator方法就可以把对象转换为一个迭代器。这与Python中的可迭代对象和迭代器的概念类似。在Python中,实现了__iter__方法就是一个可迭代对象,再实现__next__方法就是一个迭代器。
Python的迭代器和可迭代对象

Iterator定义

pub trait Iterator{type Item;fn next(&mut self) -> Option<Self::Item>;
}

实现了Iterator的对象就是一个迭代器类型

IntoIterator

实现了IntoIterator就可以使用for in循环了

pub trait IntoIterator {type Item;type IntoIter: Iterator<Item=Self::Item>;fn into_iter(self) -> Self::IntoIter;
}// 实现了Iterator可以自动实现IntoIterator
impl<I: Iterator> IntoIterator for I {type Item = I::Item;type IntoIter = I;#[inline]fn into_iter(self) -> I {self}
}

示例


struct Node<T> {value: T,next: Option<Box<Node<T>>>
}struct LinkedList<T> {head: Option<Box<Node<T>>>,length: usize
}impl <T> Node<T> {fn new(value: T) -> Self {Node { value, next: None }}
}impl <T> LinkedList<T> {fn new() -> Self {LinkedList { head: None, length: 0 }}fn push_front(&mut self, value: T) {let new_node = Box::new(Node{value, next: self.head.take()});self.head = Some(new_node);self.length += 1;}fn pop_front(&mut self) -> Option<T> {self.head.take().map(|node| {self.head = node.next;self.length -= 1;node.value})}fn peek(&self) -> Option<&T> {self.head.as_ref().map(|node| {&node.value})}fn len(&self) -> &usize {&self.length}fn is_empty(&self) -> bool {*self.len() == 0}fn contains(&self, value: T) -> bool where T: PartialEq{let mut current = &self.head;while let Some(node) = current {if node.value == value {return true;}current = &node.next;}false}fn reverse(&mut self) {let mut prev = None;let mut current = self.head.take();while let Some(mut node) = current {let next = node.next.take();node.next = prev;prev = Some(node);current = next;}self.head = prev;}fn clear(&mut self) {self.length = 0;self.head = None;}fn reverse_recursive(&mut self) {fn recusive<T> (head: Option<Box<Node<T>>>, pre: Option<Box<Node<T>>>) -> Option<Box<Node<T>>> {if head.is_none() {return pre;}let mut cur = head.unwrap();let next: Option<Box<Node<T>>>  = cur.next.take();cur.next = pre;recusive(next, Some(cur))}self.head = recusive(self.head.take(), None);}fn reverse_recursive2(&mut self) {fn recusive<T> (head: Option<Box<Node<T>>>, pre: Option<Box<Node<T>>>) -> Option<Box<Node<T>>> {match head {Some(mut node) => {let next = node.next.take();node.next = pre;recusive(next, Some(node))},None => pre}}}}struct IntoIter<T> {list: LinkedList<T>
}struct Iter<'a, T> {next: Option<&'a Node<T>>
}struct IterMut<'a, T> {next: Option<&'a mut Node<T>>
}impl<T> Iterator for IntoIter<T> {type Item = T;fn next(&mut self) -> Option<Self::Item> {self.list.pop_front()}}impl<T> IntoIterator for LinkedList<T> {type Item = T;type IntoIter = IntoIter<T>;fn into_iter(self) -> Self::IntoIter {IntoIter {list: self}}}impl <'a, T> Iterator for Iter<'a, T> {type Item = &'a T;fn next(&mut self) -> Option<Self::Item> {self.next.map(|node| {self.next = node.next.as_deref();&node.value})}
}impl<T> LinkedList<T> {pub fn iter(&self) -> Iter<'_, T> {Iter { next: self.head.as_deref() }}
}impl<'a, T> Iterator for IterMut<'a, T> {type Item = &'a mut T;fn next(&mut self) -> Option<Self::Item> {self.next.take().map(|node| {self.next = node.next.as_deref_mut();&mut node.value})}
}impl<T> LinkedList<T> {pub fn iter_mut(&mut self) ->IterMut<'_, T> {IterMut { next: self.head.as_deref_mut() }}
}fn main() {let mut list = LinkedList::new();list.push_front(1);list.push_front(2);list.push_front(3);assert_eq!(list.pop_front(), Some(3));assert_eq!(list.pop_front(), Some(2));assert_eq!(list.pop_front(), Some(1));assert_eq!(list.pop_front(), None);}
http://www.jsqmd.com/news/57134/

相关文章:

  • 适合幼儿园开展的STEM课程品牌介绍及分析
  • 分库分表全面总结
  • 2025年深圳品牌策划公司推荐排行榜:深圳品牌策划公司能整合
  • 2025年中国十大网店代运营公司推荐:代运营哪家强?
  • 2025年户外橡胶地垫制造厂权威推荐榜单:减震橡胶地垫/公园橡胶地垫/复合橡胶地垫源头厂家精选
  • 靠谱的国际短信验证码平台,短信验证码服务商盘点,兼顾速度、安全与成本控制!
  • 【JPCS出版 | EI检索】第七届国际科技创新学术交流大会暨机械工程与自动化国际学术会议(MEA 2025)
  • 这个代码有什么用
  • 2025年日字扣生产厂家权威推荐榜单:箱包塑料配件‌/塑料制品‌/塑胶扣具‌源头厂家精选
  • 非接图标(适用于屏幕大小为240*320)
  • 2025年磷酸铁回转窑生产厂家权威推荐榜单:回转窑干燥设备‌/磷酸铁锂回转窑‌/大豆渣回转窑干燥机‌源头厂家精选
  • JavaScript基础笔记碎片-对象、数组、Map与Set
  • java17版本,用IDEA开发,在JavaFX中无法找到com.google.gson。
  • 2025手机配件到迪拜物流专线送仓TOP5权威推荐:甄选企业
  • Visual Studio Code 轻量不简陋!VS Code:零基础编程者的第一款「万能编辑器」安装+中文设置步骤
  • 推荐几家海外展会推广公司,五家效果不错的海外展会营销推广平台详细介绍
  • 2025年12月AI 编程代码生成效率实战推荐:技术性能与应用场景的全面分析
  • 我是皇帝
  • 数字屋打包流程
  • 2025年食用油脂企业性价比与满意度排名:油一堂食品性价比好
  • 2025年进口无硫纸厂家权威推荐榜单:防潮纸/硅片间隔纸/丝印白纸源头供应商精选
  • setInterVal长时间运行卡顿,采用setTimeout代替setInterval
  • 2025年下半年四川喷塑优质厂家推荐排行榜:成都汇元满机械制造有限公司领衔十大品牌
  • BetterGI:基于计算机视觉的《原神》游戏自动化辅助工具
  • 2025年下半年工业大吊扇工厂Top 5推荐指南:专业选择与比较
  • 离散对数问题和求解
  • 2025年下半年央国企就业辅导机构综合评估与选择指南
  • 完整教程:【内存管理】深入理解CR3寄存器:进程地址空间切换与虚拟内存管理的核心枢纽
  • 2025年下半年永磁工业风扇工厂综合选购指南
  • 2025年12月优质螺栓厂家电话精选:外六角螺栓/U型螺栓/地脚螺栓/预埋螺栓厂家联系方式 + 实用选择指南建筑 / 工业用螺栓选型参考