How to define generic type parameter such that it implements certain traits

It is a syntax question.

I have a function which takes as input any type which is deriving serde::Serialize.

#[derive(Serialize)]
struct Test { ... }

fn some_fn<T /*implements Serialize*/>(param: T) { ... }

How do I achieve this? And what if there are muliple such constraints which I want to apply on the type T.

//         vvvvvvvvvvvv
fn some_fn<T: Serialize>(param: T) { ... }

This is a trait bound (in the Book). If you want to make T implement (for example) Serialize and Debug, use a bound T: Serialize + Debug. (also in the Book).

This is syntax sugar for the equivalent where clause (surprise! also in the Book):

fn some_fn<T>(param: T)
where
    T: Serialize
{
    ...
}

Really, this whole answer is just rehashing the “traits as parameters” section of the traits subchapter of the Book. Go look at it. If you haven’t yet, you should really read the whole book.

5 Likes