Skip to content

Instantly share code, notes, and snippets.

@hucancode
Last active September 15, 2023 07:00
Show Gist options
  • Save hucancode/36d1292b9be27a142923ac782e3c0190 to your computer and use it in GitHub Desktop.
Save hucancode/36d1292b9be27a142923ac782e3c0190 to your computer and use it in GitHub Desktop.
Learn Rust Option<Box<T>>(which is Recursivable Nullable Single Owner Object) by implementing a linked list
use std::fmt::Debug;
#[derive(Debug)]
struct Node {
value: i32,
next: Option<Box<Node>>,
}
impl Node {
fn new(x: i32) -> Self {
Self {
value: x,
next: None,
}
}
fn new_boxed(x: i32) -> Box<Self> {
return Box::new(Self::new(x));
}
fn prepend(self, x: i32) -> Self {
Self {
value: x,
next: Some(Box::new(self)),
}
}
fn append_node(&mut self, other: Box<Self>) -> &mut Self {
self.next = Some(other);
return self.next.as_mut().unwrap();
}
fn append(&mut self, x:i32) -> &mut Self {
self.append_node(Node::new_boxed(x))
}
fn for_each(&self, callback: fn(i32)) {
callback(self.value);
let mut node = &self.next;
while let Some(ref next) = node {
callback(next.value);
node = &next.next;
}
}
}
fn main() {
let mut head = Node::new_boxed(1);
head.append(2)
.append(3)
.append(4);
let head = head.prepend(0)
.prepend(-1)
.prepend(-2)
.prepend(-3);
head.for_each(|x| print!("{}, ",x));
// println!("{:?}", head);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment