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
.
Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O(1) indexing and push and pop operations in vector also take O(1) complexity.
x is a Vec. last() returns an Option<&T>. let x = items[items. len()-1];
A contiguous growable array type, written as Vec<T> , short for 'vector'.
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 amemmove
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With