Vec - Removing an element at an index without removing elmenet

⚓ rust    📅 2025-05-06    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 59 days ago. The information described in this article may have changed.

Hello,

I am trying to implement a circular buffer using Vec. Vec::insert() transfers ownership to the Vec. I am trying to find a way to be able to remove/extract the element from the Vec without "deleting" the "index" where the element is present.

I am running into the error "cannot move out of index of Vec<>". I thought of using an Option<>, but ran into same issue.

Following is code snippet of the API

pub struct CircularBuffer<T> {
    // ...
}

impl<T> CircularBuffer<T> {
    pub fn new(capacity: usize) -> Self { todo!() }
    pub fn write(&mut self, element: T) -> Result<(), Error> { todo!() }
    pub fn read(&mut self) -> Result<T, Error> { todo!() }
}

Would appreciate any pointers.
(In C++ I would use an array of ptrs, setting element to null when value at an index is empty.).

Regards,
Ahmed.

6 posts - 5 participants

Read full topic

🏷️ rust_feed