Guest User

Untitled

a guest
Apr 20th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. struct Item {
  2. test: u32,
  3. }
  4. struct PackBox {
  5. items: Vec<Item>,
  6. }
  7. struct Inventory {
  8. unpack_items: Vec<Item>,
  9. boxes: Vec<PackBox>,
  10. }
  11. fn main() {
  12. let mut inventory = Inventory {
  13. boxes: vec![PackBox {
  14. items: vec![Item { test: 0 }],
  15. }],
  16. unpack_items: vec![Item { test: 1 }, Item { test: 2 }, Item { test: 3 }],
  17. };
  18.  
  19. /*
  20.  
  21. Unpack all boxes into the inventory
  22. */
  23. {
  24. // The extra { } scope here is necessary because boxitems_iter has borrowed inventory.
  25. // It needs to go out of scope and release the borrow in ordor for those asserts at the bottom to compile.
  26. let boxitems_iter = inventory
  27. .boxes
  28. .drain(..) // Drain returns an iterator that takes ownership of all the vec's elements, and leaves the vec empty
  29. .flat_map(|packbox| packbox.items.into_iter()); // into_iter consumes the vec itself (as opposed to drain which consumes only the vec's elements)
  30.  
  31. // extend will append all of the iterator's elements to the vector.
  32. inventory.unpack_items.extend(boxitems_iter);
  33. }
  34.  
  35. // unpack_items contains all four of the items, and there are no boxes left.
  36. assert_eq!(inventory.unpack_items.len(), 4);
  37. assert_eq!(inventory.boxes.len(), 0);
  38. }
Add Comment
Please, Sign In to add comment