当前位置: 首页 > 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.gsyq.cn/news/67415.html

相关文章:

  • 适合幼儿园开展的STEM课程品牌介绍及分析
  • 分库分表全面总结
  • 2025年中国十大网店代运营公司推荐:代运营哪家强?
  • 2025年户外橡胶地垫制造厂权威推荐榜单:减震橡胶地垫/公园橡胶地垫/复合橡胶地垫源头厂家精选
  • 靠谱的国际短信验证码平台,短信验证码服务商盘点,兼顾速度、安全与成本控制!
  • 【JPCS出版 | EI检索】第七届国际科技创新学术交流大会暨机械工程与自动化国际学术会议(MEA 2025)
  • JavaScript基础笔记碎片-对象、数组、Map与Set
  • 数字屋打包流程
  • 2025年12月优质螺栓厂家电话精选:外六角螺栓/U型螺栓/地脚螺栓/预埋螺栓厂家联系方式 + 实用选择指南建筑 / 工业用螺栓选型参考
  • 2025年下半年工业风扇工厂综合推荐指南:十佳厂家全方位解析
  • jkd和notepad++
  • 开源了我的第一个 Chrome 扩展:CNB Workspace Manager
  • 护手霜挑选必备指南:2025十大防干裂品牌深度剖析!持久保湿滋润呵护双手
  • 如何在Stimulsoft图表中创建自动系列(Auto Series)——实战示例解析
  • 2025年度裁断机厂商排名,裁断机厂家哪家售后好
  • xxl-job打包出现Could not determine gpg version异常
  • 冰蓝科技正式发布全新纯前端文档编辑产品 —— Spire.WordJS
  • 第一天敏捷冲刺博客
  • 2025年北京天津河北上海江苏印刷精品定制公司推荐:专业的印
  • top flow
  • 裁断机厂家选哪家好?裁断机服务商价格哪个合理?
  • 2025年日化产品袋制袋机优质厂家权威推荐榜单:高速三边封直立袋全自动制袋机‌/咖啡袋制袋机‌/塑料制袋机‌源头厂家精选
  • 视频汇聚平台EasyCVR助力打造太阳能供电远程视频监控系统
  • 相册链接
  • Elasticsearch 7.0 介绍与配置详解 - 指南
  • 企业管理 AI 应用服务商推荐:从场景覆盖到生态整合,用友BIP端到端解决方案引领行业
  • 2025年12月护墙板定制工厂TOP10实力榜:更有实木楼梯/衣柜/橱柜/木门等全品类对比,市场口碑+行业数据选购指南
  • 嵌入式工程师往后怎么发展?
  • 在曲阳县老家农村盖房子,靠谱的自建房公司去哪里找?河北保定曲阳县自建房公司/机构权威测评推荐排行榜
  • 曲阳县农村自建房公司口碑推荐榜。2026年自建房公司权威测评优选。