How do i implement a custom vector?

Hi, I am very new to rust, the initial learning curve was nostalgic, and reminded me my beginning in programming.

I wrote my first project, where i was storing runtime logs, in a Vec<LogLine> (used later by other parts of the application).

When the vector is filling up, i would like to delete the oldest logs, to make room for the new, initially i was using truncate, until i figured thats deleting the new ones, not the old once.

Next option was to shift everything left and then truncate, however thats quite expensive.

I tried to to wrtie a custom vector, that stores the current zero, and rotating around after reaching max


impl rotating_vector {
    fn new(&self, max:i32) {
        rotating_vector {
            loglines:Vec::new(),
            zero:0,
            max:max
        }
    }
    fn push<T>(&self, item: T){
        self.loglines[self.zero]=item;
        self.zero=self.zero % self.max;
    }
    fn stringify(){
        
    }
}

I am unable to set in my mind

#1 How to make the class generic and pass the generic type to the internal vector?
#2 who will drop the elements when overriding by the new round?
#3 How can i inherit the defualt vector methods?

This already exists as std::collections::VecDeque, but if you want to build your own on top of a vector, I would probably make the item type an Option and have the elements at the start all be None.

You wouldn't be able to inherit the ordinary vector methods, or even the slice methods due to the Option though. That said, you can provide iterators and the iterators will have all the usual iterator methods.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.