Extend Vec behaviour

I would like to extend the vector iterator.
For example,

let mut v:Vec<Box<dyn Any>>=vec![any0,any1,any2,any3,any4,any5,any6,any7];
// when v.availableIndexes=vec![1,5,7] "which should be a pub(crate) property" 
// then v.len()=3
for i in 0..v.len(){
// v[0]=any1;
// v[1]=any5;
// v[2]=any7;
// v[3] => error: index out of range

Do I have to create an iterator or is it possible to extend Vec iterator behaviour ?
Thank you in advance for your help.

I'm not exactly sure what you are after. Does std::iter::Extend do what you want? It is implemented for Vec<T>, so you should be able to extend v by calling v.extend(some_iterator), where some_iterator is an iterator containing Box<dyn Any> elements.

I'm guessing that you want to cause the iterator for v to only return the indexes in availableIndexes, is that right?

If so you could iterate availableIndexes and map to the element in v:

// I've used characters as an example
let mut v: Vec<char> = vec!['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

// Should be a pub(crate) property
let available_indexes = vec![1, 5, 7];

for c in available_indexes.iter().map(|x| v[*x]) {



Well, I know about Extend and how to iterate over a vector.
My goal is to build a Struct which implements the expected behaviour: a kind of VecShadowIndexes.
It will make available only selected indexes.
I think I have to override a Vec (don't know if this is possible in Rust) or code a Vec from source and include my own behaviour...

You could do that with the code I posted.

Why do you want to override Vec? There is nothing wrong with a separate function to iterate in any way you'd like.

EDIT: Here is one way to write such a function, assuming that the values could be any type T and you want to pass in the indexes rather than use a static field:

fn iter_only_indexes<'a, 'b, T>(
    values: &'a [T],
    indexes: &'b [usize],
) -> impl Iterator<Item = &'a T>
    'b: 'a,
    indexes.iter().map(|x| &values[*x])

Maybe you want to make a container that only holds values in some of the indices? Then you insert new values at new indices to your shadow-vector, remove existing values, or access values by their indices.

If that's what you want, you should try using HashMap.

I finally wrapped a Vec in a custom struct...

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.