-
-
Save greister/1722e681bcc02d9d72cfede2b20a1531 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or 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
// Define a structure named `List` containing a `Vec`. | |
use std::fmt; | |
use std::ops::Deref; | |
struct List(Vec<i32>); | |
impl Deref for List { | |
type Target = Vec<i32>; | |
fn deref(&self) -> &Vec<i32> { | |
&self.0 | |
} | |
} | |
impl fmt::Display for List { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
// Dereference `self` and create a reference to `vec` | |
// via destructuring. | |
let List(ref vec) = *self; | |
try!(write!(f, "[")); | |
// Iterate over `vec` in `v` while enumerating the iteration | |
// count in `count`. | |
for (count, v) in vec.iter().enumerate() { | |
// For every element except the first, add a comma | |
// before calling `write!`. Use `try!` to return on errors. | |
if count != 0 { try!(write!(f, ", ")); } | |
try!(write!(f, "{}", v)); | |
} | |
// Close the opened bracket and return a fmt::Result value | |
write!(f, "]") | |
} | |
} | |
fn main() { | |
let v = List(vec![1, 2, 3]); | |
println!("{:?}", v.len()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment