Mixed types in Vec<T>

Are there any plans, to make mixed type vectors possible?

I am thinking about something like this:

let data: Vec<impl ToString> = vec!["&str", String::from("String")];

No - each element of the vector needs to have the same fixed size for indexing to work.

You can instead use trait objects: Vec<Box<dyn ToString>>.


You can use a vector of trait objects

let data : Vec<Box<dyn ToString>> = vec![Box::new("str"), Box::new(String::from("String"))];
for toString in data {
    println!("{}", toString.to_string());

In a talk about Haskell, I've heard the following ancient functional programming proverb:

– "I really-really-really need a heterogeneous type!"
And then, when you've used Haskell for six months, you're like:
– "Pffft, I was so foolish, I never needed that heterogeneous type, ever."

Just use an enum. (Or, as others pointed out, dynamic dispatch.)


Yup, in this case Cow<str> fits precisely.


If you really want a mixed type vector (or formally, a heterogeneous list), you can use frunk, as specified by the HList trait which you can create with the hlist macro

1 Like

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