Attach where clause to generic function?


Is it possible to attach a where clause to a generic function? (One of the generic types has lots of traits).

Looking at there is clearly a way to attach it to an “impl”, but I don’t see how to attach it to a function.


Try this:

fn foo<T, U, W>() 
where T: TraitA + 'Lifetime,
    U: TraitB + Deref<Target = T> + 'Lifetime2,
    W: ?Sized {

This is similar to C# if you’ve used that before:

namespace Test {
    class Example {
         public static void UsesGenerics<T, D>(D Data) where D: IEnumerable<T> {}
1 Like

@OptimisticPeach : Worked thanks! Didn’t realize where clauses can be placed between type sig and starting {

1 Like

Yeah, the where clause is also placed in this odd location in the case of tuple structs:

struct Bar<T>(T) where T: Trait;

And in this case:

use std::ops::Deref;

trait Foo<T> where Self: Deref<Target = T> {}
1 Like

I was not aware where clause could be attached to structs at all.

Can it also be attached to:

struct Bar<T> {
  cat: T,
  dog: Vec<T>,


1 Like

Yes, it can be attached to any required generic parameter:

struct Bar<T> 
where T: Life {
    cat: [T; 9],
    dog: T

trait Bar2<T> where Self: OtherTrait<T> {}

union Bar3<T> where T: Deref<Target = str> {}

enum Bar4<T> where T: std::ops::Add<T> {}

Also please do note, that technically unit structs can have generics too:

struct Foo<T> where T: std::fmt::Debug;

But the only case (Or at least best example) allowed is std::marker::PhantomData which is declared like so:

pub struct PhantomData<T:?Sized>;
1 Like