vectorrustmemmove

How are elements of a vector left-shifted in Rust?


Is there a safe way to left-shift elements of a vector in Rust? (vec![1, 2, 3] becomes vec![3] when left-shifted two places). I'm dealing with Copy types, and I don't want to pay a penalty higher than what I would with a memmove.

The only solution I've found is unsafe: use memmove directly via ptr::copy.


Solution

  • I would use Vec::drain.

    You can call it with a range of the elements you want to remove, and it'll shift them over afterwards. Example: (playpen)

    fn main() {
        let mut v = vec![1, 2, 3];
    
        v.drain(0..2);
    
        assert_eq!(vec![3], v);
    }
    

    One other note:

    I'm dealing with Copy types, and I don't want to pay a penalty higher than what I would with a memmove.

    Worth noting that moving is always a memcpy in Rust, so the Copy vs non-Copy distinction doesn't matter here. It'd be the same if the types weren't Copy.