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")];
1 Like

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>>.

3 Likes

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());
}
5 Likes

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.)

8 Likes

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

4 Likes

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.