rustvectoriteratorslice

How do I move as many elements as possible from a Vec into a pre-existing slice?


I have src: Vec<Foo> and dst: &mut [Foo]. I want to move as many elements as possible from src into dst. Specifically:

For example, pretending Foo was i32 (but it should work for non-Copy types too):

I know I could loop manually and move one element at a time, but it seems like there should be a Drain-like approach instead.


Solution

  • This is easy to do just by figuring out how many elements you can move (which is the minimum of both lengths) and then using drain to remove those elements and place them in the destination.

    pub fn move_many<T>(src: &mut Vec<T>, dst: &mut [T]) {
        let count = src.len().min(dst.len());
    
        for (s, d) in src.drain(0..count).zip(dst) {
            *d = s;
        }
    }
    

    (Playground)