Day 13l: Implementing Custom Vector-Like Collections

Venkat Annangi
Venkat Annangi
08/10/2024 02:38 1 min read 63 views
#rust-vectors #rust #108 days of rust

Day 13l: Implementing Custom Vector-Like Collections

Introduction

While Rust’s built-in Vec is powerful, you may need to create your own custom vector-like collection. In this session, we’ll walk through building a simplified vector structure that mimics some of the behaviors of Vec.

Creating a Simple Vector Wrapper

Here’s a simple implementation of a custom vector-like structure using Rust’s Vec under the hood.

struct MyVector<T> {

    data: Vec<T>,

}



impl<T> MyVector<T> {

    fn new() -> Self {

        MyVector { data: Vec::new() }

    }



    fn push(&mut self, value: T) {

        self.data.push(value);

    }



    fn get(&self, index: usize) -> Option<&T> {

        self.data.get(index)

    }

}



fn main() {

    let mut my_vec = MyVector::new();

    my_vec.push(1);

    my_vec.push(2);

    println!("{:?}", my_vec.get(1));  // Output: Some(2)

}

Conclusion

Building custom collections in Rust allows you to extend or modify existing functionality. While Rust’s Vec is highly optimized, learning to implement your own version gives you deeper insights into how collections work.

Comments