其他分享
首页 > 其他分享> > rust iter 2

rust iter 2

作者:互联网

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