When should I use `drain` vs `into_iter`?

后端 未结 2 629
挽巷
挽巷 2021-01-03 20:07

On the surface, it looks like both drain and into_iter provide similar iterators, namely over the values of the collection. However, they are different:

fn m         


        
2条回答
  •  悲哀的现实
    2021-01-03 20:16

    After using drain, the Vec is empty but the storage previously allocated for its elements remains allocated. This means that you can insert new elements in the Vec without having to allocate storage for them until you reach the Vec's capacity.

    Note that before you can use the Vec again, you must drop all references to the Drain iterator. Drain's implementation of Drop will remove all elements that hadn't been removed from the Vec yet, so the Vec will be empty even if you didn't finish the iteration.

提交回复
热议问题