Advertisement
Guest User

Untitled

a guest
Apr 30th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. // Define a structure named `List` containing a `Vec`.
  2.  
  3. use std::fmt;
  4. use std::ops::Deref;
  5.  
  6. struct List(Vec<i32>);
  7.  
  8. impl Deref for List {
  9. type Target = Vec<i32>;
  10.  
  11. fn deref(&self) -> &Vec<i32> {
  12. &self.0
  13. }
  14. }
  15.  
  16. impl fmt::Display for List {
  17. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  18. // Dereference `self` and create a reference to `vec`
  19. // via destructuring.
  20. let List(ref vec) = *self;
  21.  
  22. try!(write!(f, "["));
  23.  
  24. // Iterate over `vec` in `v` while enumerating the iteration
  25. // count in `count`.
  26. for (count, v) in vec.iter().enumerate() {
  27. // For every element except the first, add a comma
  28. // before calling `write!`. Use `try!` to return on errors.
  29. if count != 0 { try!(write!(f, ", ")); }
  30. try!(write!(f, "{}", v));
  31. }
  32.  
  33. // Close the opened bracket and return a fmt::Result value
  34. write!(f, "]")
  35. }
  36. }
  37.  
  38. fn main() {
  39. let v = List(vec![1, 2, 3]);
  40. println!("{:?}", v.len());
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement