Test
Test

Reputation: 1720

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(...)
}

Upvotes: 1

Views: 617

Answers (1)

cdhowie
cdhowie

Reputation: 169028

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.

Upvotes: 2

Related Questions