Can array slices not consume during iteration?

I have a function that takes some generic elements, which I wish to mutate, collect and return. As I understand it, calling into_iter creates a consuming iterator, while map takes those owned values. This is the case for Vec below, however it is not the case for the &[T] array. Why is this not the case? And while this is in no way an issue, is there such a way for the map method to take owned elements of the &[T] type?

fn iter_map<T>(array: &[T], vec: Vec<T>) {
    // Why is this type `&T`?:
    array.into_iter().map(|t: &T| ());
    // In contrast to this vector, for example:
    vec.into_iter().map(|t: T| ());
}

That's not an array, that's called a slice. As for why you are getting a &T rather than a T, that's because you are iterating over &[T]. The same thing would happen if you received a reference to the vector(&Vec).

2 Likes

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.