How to create function in which I can pass Vec and VecDeque?

Let imagine that I want to implement my own algorithm for Vec and VecDeque collections.

How to write a function which consume both of these collections as agrument?

fn cool_algo( v : ??? ) {
    //impl
}

Depending on what you need you will either need to make a new trait, or (if you only need to iterate over them) you can take an IntoIterator<Item = ???>

fn cool_algo( v : impl IntoIterator<Item = ???>) {
    //impl
}

Unfortunately, I would like to have random access to vector's elements, so this solution doesn't fit to me.

If you need random access, would Index<usize, Output = ???> work? If not, you will have to make your own trait that both Vec<_> and VecDeque implement,

pub trait VecLike {
    type Item;

    fn get(&self, index: usize) -> Option<&Self::Item>;
    fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>;

    // ... whatever else you need
}

impl<T> VecLike for Vec<T> {
    type Item = T;

    fn get(&self, index: usize) -> Option<&Self::Item> { self.as_slice().get(index) }
    fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item> { self.as_slice_mut().get_mut(index) }
}

Thanks, sounds like great canonical Rust solution. If you want some requirements from input data, make a trait which user can implement.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.