python;gutter:true;
use std::ptr;
use std::fmt::{ Display, Formatter, Result };</p>
<p>pub struct Node {
value: i32,
next: *mut Node
}</p>
<p>impl Node {
pub fn new(val: i32) -> Self {
Node {
value: val,
next: ptr::null_mut(),
}
}
}</p>
<p>pub struct List {
head: *mut Node
}</p>
<p>impl List {
pub fn new() -> Self {
List {
head: ptr::null_mut()
}
}</p>
<pre><code>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;
}
}
}
</code></pre>
<p>}</p>
<p>impl Display for List {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "List: {}", self)
}
}</p>
<p>impl IntoIterator for List {
type Item = i32;
type IntoIter = ListIntoIterator;</p>
<pre><code>fn into_iter(self) -> Self::IntoIter {
ListIntoIterator { list: self }
}
</code></pre>
<p>}</p>
<p>pub struct ListIntoIterator {
list: List,
}</p>
<p>impl Iterator for ListIntoIterator {
type Item = i32;
fn next(&mut self) -> Option {
let mut start = self.list.head;
unsafe {
if (<em>start).next != ptr::null_mut() {
start = (</em>start).next;
}</p>
<pre><code> return Some((*start).value);
}
}
</code></pre>
<p>}</p>
<p>fn main() {
let mut list1 = List::new();
list1.add(3);
list1.add(6);</p>
<pre><code>// let mut list2 = List::new();
for _i in list1.into_iter() {
println!("{:?}", &_i);
// for j in _i.into_iter() {
// println!("{}", j);
// }
};
</code></pre>
<p>}
Original: https://www.cnblogs.com/pythonClub/p/16528150.html
Author: CrossPython
Title: rust iter 2
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/15780/
转载文章受原作者版权保护。转载请注明原作者出处!