Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust: Extend Existing Data Structure Via an External Library

How does one take an existing data structure (vec, hashmap, set) and extend the methods on it via an external library?

fn main() {
    let vec = vec![1, 2, 3];
    vec.my_new_method(...)
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can take advantage of the fact that a crate defining a trait can implement that trait on whatever type it wants. Here’s a simple example of a combined "shift and then push" function. First it will shift the first element out of the vector (if there is one), then it will push the argument on to the end of the vector. If there was a shifted element, it is returned. (This is a bit of a silly operation, but works to demonstrate this technique.)

First we declare the trait, with the signature of the method(s) we want to add:

trait VecExt<T> {
    fn shift_and_push(&mut self, v: T) -> Option<T>;
}

Now we can implement the trait for Vec<T>:

impl<T> VecExt<T> for Vec<T> {
    fn shift_and_push(&mut self, v: T) -> Option<T> {
        let r = if !self.is_empty() { Some(self.remove(0)) } else { None };
        
        self.push(v);
        
        r
    }
}

Now, anywhere that VecExt is brought into scope with use (or by being in the same source file as its declaration) this extension method can be used on any vector.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading