How to convert between Vectors of different types

I would have expected that if I have implemented From<T> for S then I get From<Vec<T>> for Vec<S> for free. However looking at the From Documentation I find nothing like this. I also cannot implement this myself, because both Vec and From are defined externally.

What is the recommended way to convert from Vec<i32> to Vec<i64>, say? In this Playground I wrote a custom from function to illustrate what I want to do. What's annoying is that this way I won't get into functions for free.

That would be the map method from the Iterator trait.

Why not? It's a coherence issue, where there can only be one applicable trait implementation.

From<Vec<T>> for Vec<U> where T: From<U> conflicts with From<X> for X: two applicable implementations for From<Vec<Y>> for Vec<Y>.

4 Likes

Thanks! Would you say that the way I do it in the Playground is alright, or is there something to improve? Can it be done for types which don't include the Clone trait?

(Since I'm quite new to Rust, I always feel a bit insecure if what I do makes any sense :upside_down_face:)

Since you are taking ownership of the input Vec, you can call into_iter() instead of iter() and then you don't need Clone.

2 Likes

As jameseb7 said, I would expect such conversion (From Vec<T> to Vec<U>) to consume the original vector.

1 Like

Thanks everyone!

If you need to use that for several types, you can write a generic function or a blanket trait implementation that avoids the problem where you accidentally re-implement the From<X> for X.

Playground

1 Like
    T: IntoIterator,
    <T as IntoIterator>::Item: Into<U>,

Can be written like this now:

    T: IntoIterator<Item: Into<U>>,
4 Likes

Nice shortcut, thanks!

And the FromIterator is there to make it more general, but it can be simplified if only Vec is desired.