Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 311
Doe Avatar asked Jul 06 '16 15:07

Doe


People also ask

How do vectors work in Rust?

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.

How do you find the last element of a vector in Rust?

x is a Vec. last() returns an Option<&T>. let x = items[items. len()-1];

What does VEC mean in Rust?

A contiguous growable array type, written as Vec<T> , short for 'vector'.


1 Answers

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.

like image 63
Steve Klabnik Avatar answered Oct 23 '22 19:10

Steve Klabnik