Created
September 29, 2024 22:32
-
-
Save robert-king/658ffac1ba7fd1eb36c82f40261b4aa6 to your computer and use it in GitHub Desktop.
rust linkedist with iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Node { | |
next: Option<Box<Node>>, | |
val: i32, | |
} | |
impl Node { | |
fn new(val: i32) -> Self { | |
Node { next: None, val } | |
} | |
fn iter_mut(&mut self) -> IterMut<'_> { | |
IterMut(Some(self)) | |
} | |
} | |
struct IntoIter { | |
cur: Option<Node>, | |
} | |
impl Iterator for IntoIter { | |
type Item = i32; | |
fn next(&mut self) -> Option<Self::Item> { | |
if let Some(cur) = self.cur.take() { | |
if let Some(nxt) = cur.next { | |
self.cur = Some(*nxt); | |
} | |
return Some(cur.val); | |
} | |
None | |
} | |
} | |
impl IntoIterator for Node { | |
type Item = i32; | |
type IntoIter = IntoIter; | |
fn into_iter(self) -> Self::IntoIter { | |
IntoIter { cur: Some(self) } | |
} | |
} | |
struct IterMut<'a>(Option<&'a mut Node>); | |
impl<'a> Iterator for IterMut<'a> { | |
type Item = &'a mut i32; | |
fn next(&mut self) -> Option<Self::Item> { | |
self.0.take().map(|node| { | |
self.0 = node.next.as_deref_mut(); | |
&mut node.val | |
}) | |
} | |
} | |
impl<'a> IntoIterator for &'a mut Node { | |
type Item = &'a mut i32; | |
type IntoIter = IterMut<'a>; | |
fn into_iter(self) -> Self::IntoIter { | |
IterMut(Some(self)) | |
} | |
} | |
fn main() { | |
let c = Node::new(3); | |
let mut b = Node::new(2); | |
b.next = Some(Box::new(c)); | |
let mut a = Node::new(1); | |
a.next = Some(Box::new(b)); | |
for val in &mut a { | |
*val *= 10; | |
} | |
for val in a { | |
println!("{val}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment