Created
April 13, 2016 11:23
-
-
Save anonymous/07639736064b19941f610e05303c4b04 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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
use std::iter::FromIterator; | |
use std::ops::Deref; | |
struct List(Option<Box<Node>>); | |
fn main() { | |
let v = vec![1, 5, 3, 8, 12, 56, 1230, 2, 1]; | |
let root: List = v.iter().cloned().collect(); | |
println!("root: {}", | |
root.0.map(|n| n.to_string()).unwrap_or(String::from("None"))); | |
} | |
impl Deref for List { | |
type Target = Option<Box<Node>>; | |
fn deref(&self) -> &Self::Target { | |
&self.0 | |
} | |
} | |
// and we'll implement FromIterator | |
impl FromIterator<i32> for List { | |
fn from_iter<I: IntoIterator<Item = i32>>(iterator: I) -> Self { | |
let mut root: List = List(None); | |
let mut prev: *mut List = &mut root; | |
for i in iterator { | |
let curr = List(Some(Box::new(Node { | |
value: i, | |
next: List(None), | |
}))); | |
unsafe { | |
(*prev) = curr; | |
prev = &mut (*prev).0.as_mut().unwrap().next; | |
} | |
} | |
root | |
} | |
} | |
struct Node { | |
value: i32, | |
next: List, | |
} | |
impl std::fmt::Display for Node { | |
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { | |
let mut cur = Some(self); | |
let mut first = true; | |
try!(write!(fmt, "[")); | |
while let Some(node) = cur { | |
if !first { | |
try!(write!(fmt, ", ")); | |
} | |
first = false; | |
try!(write!(fmt, "{}", node.value)); | |
cur = node.next.as_ref().map(|n| &**n); | |
} | |
try!(write!(fmt, "]")); | |
Ok(()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment