标签:mut self List iter next null ptr rust
use std::ptr; use std::fmt::{ Display, Formatter, Result }; pub struct Node { value: i32, next: *mut Node } impl Node { pub fn new(val: i32) -> Self { Node { value: val, next: ptr::null_mut(), } } } pub struct List { head: *mut Node } impl List { pub fn new() -> Self { List { head: ptr::null_mut() } } pub fn add(&mut self, value: i32) { if self.head == ptr::null_mut() { self.head = &mut Node::new(value); return () } let mut _ptr1 = self.head; // let mut _ptr3 = ptr::null_mut(); // self.head = _ptr3; unsafe { while (*_ptr1).next != ptr::null_mut() { _ptr1 = (*_ptr1).next; } } let mut _ptr2 = ptr::null_mut(); _ptr2 = &mut Node::new(value); unsafe { if (*_ptr1).next == ptr::null_mut() { (*_ptr1).next = _ptr2; } } } } impl Display for List { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "List: {}", self) } } impl IntoIterator for List { type Item = i32; type IntoIter = ListIntoIterator; fn into_iter(self) -> Self::IntoIter { ListIntoIterator { list: self } } } pub struct ListIntoIterator { list: List, } impl Iterator for ListIntoIterator { type Item = i32; fn next(&mut self) -> Option<i32> { let mut start = self.list.head; unsafe { if (*start).next != ptr::null_mut() { start = (*start).next; } return Some((*start).value); } } } fn main() { let mut list1 = List::new(); list1.add(3); list1.add(6); // let mut list2 = List::new(); for _i in list1.into_iter() { println!("{:?}", &_i); // for j in _i.into_iter() { // println!("{}", j); // } }; }
标签:mut,self,List,iter,next,null,ptr,rust 来源: https://www.cnblogs.com/pythonClub/p/16528150.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。