Is it possible to have a generic function that takes an arbitrary number of parameters?

60 Views Asked by At

I know that rust does not have variadics. And I know that macros are one possible way to emulate them. However, I am interested in how traits can be used for this purpose.

For example, the Bevy ECS system can take functions with arbitrary parameter combinations in their signature, provided the arguments implement a given trait.

I would like to better understand how this mechanism works.

1

There are 1 best solutions below

0
BallpointBen On

It's not actually an arbitrary number of type parameters; Rust does not support this (yet). The most common solution is to use a macro to generate implementations for a number of type parameters up to some fixed limit. For instance, Reflect is implemented for up to 12 type parameters via a macro_rules! macro here. This is also common throughout the stdlib, which also uses it (for instance, to implement From<(T, ..., T)> for [T; N] and vice versa, for N at most 12).