How do I implement a trait with a generic method?

Type parameters in functions and methods are universal. This means that for all trait implementers, Trait::method<T> must be implemented for any T with the exact same constraints as those indicated by the trait (in this case, the constraint on T is only the implicit Sized).

The compiler’s error message that you indicated suggests that it was still expecting the parameter type T. Instead, your Struct implementation is assuming that T = u8, which is incorrect. The type parameter is decided by the caller of the method rather than the implementer, so T might not always be u8.

If you wish to let the implementer choose a specific type, that has to be materialized in an associated type instead.

trait Trait {
    type Output;

    fn method(&self) -> Self::Output;
}

struct Struct;

impl Trait for Struct {
    type Output = u8;

    fn method(&self) -> u8 {
        16
    }
}

Read also this section of The Rust Programming Language: Specifying placeholder types in trait definitions with associated types.

See also:

Leave a Comment