Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Item {
- test: u32,
- }
- struct PackBox {
- items: Vec<Item>,
- }
- struct Inventory {
- unpack_items: Vec<Item>,
- boxes: Vec<PackBox>,
- }
- fn main() {
- let mut inventory = Inventory {
- boxes: vec![PackBox {
- items: vec![Item { test: 0 }],
- }],
- unpack_items: vec![Item { test: 1 }, Item { test: 2 }, Item { test: 3 }],
- };
- /*
- Unpack all boxes into the inventory
- */
- {
- // The extra { } scope here is necessary because boxitems_iter has borrowed inventory.
- // It needs to go out of scope and release the borrow in ordor for those asserts at the bottom to compile.
- let boxitems_iter = inventory
- .boxes
- .drain(..) // Drain returns an iterator that takes ownership of all the vec's elements, and leaves the vec empty
- .flat_map(|packbox| packbox.items.into_iter()); // into_iter consumes the vec itself (as opposed to drain which consumes only the vec's elements)
- // extend will append all of the iterator's elements to the vector.
- inventory.unpack_items.extend(boxitems_iter);
- }
- // unpack_items contains all four of the items, and there are no boxes left.
- assert_eq!(inventory.unpack_items.len(), 4);
- assert_eq!(inventory.boxes.len(), 0);
- }
Add Comment
Please, Sign In to add comment