Reputation: 913
I have a struct that I want to be able to accept a variable amount of Types. In C++, the language I used most, there are type packs which have a syntax like this:
template<typename ...Ts> // Capture types
struct Foo {
std::tuple<Ts...> Bar; // Unpack types
};
As far as I have seen on my research there isn't something similar like this in rust, but there is a type
-type, so I thought there might be a way to use an array of types for this:
struct Foo<Ts: [type]> {
}
This, however, does not compile. I have also tried this:
struct Foo {
Bar: [type]
}
let foo = Foo { Bar: [i32, usize] };
But the rust compiler gives the error that the type
-type is not actually not a type at all.
Upvotes: 1
Views: 593
Reputation: 43872
Rust does not have variadic generics. The alternative to use will depend on the details of your application; here are two possibilities:
Use tuples. That is, you have a struct Foo<T: MyArgs> {}
where MyArgs
is a trait that is implemented for tuples ()
, (T,)
, (T,U)
, (T,U,V)
and so on up to the maximum number of types you want to support.
(This is how Rust's function traits handle argument lists. Unfortunately, you can't currently take any benefit from that.)
Use “heterogenous lists” such as are provided by hlist
or frunk
. Here you build type-level linked lists — sort of like Foo<(T, (U, (V, ())))>
except with dedicated types instead of tuples, and some helper macros for making it more readable. This allows you to support arbitrary numbers of types, provided you can express your problem in terms of type-level recursion/induction (by defining your own trait which is implemented for the list types).
Upvotes: 2