Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Created April 30, 2016 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/5afd6bf357d5bce6aa97d884ee01545f to your computer and use it in GitHub Desktop.
Save anonymous/5afd6bf357d5bce6aa97d884ee01545f to your computer and use it in GitHub Desktop.
Shared via Rust Playground
// 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