Rust invoke trait method on generic type parameter

rust, traits

Solution

As Aatch mentioned, this isn't currently possible. A workaround is to use a dummy parameter to specify the type of `Self`:

pub trait TypeTrait {
    fn type_id(_: Option<Self>) -> u16;
}

pub struct CustomType {
    // fields...
}

impl TypeTrait for CustomType {
    fn type_id(_: Option<CustomType>) -> u16 { 0 }
}

pub fn get_type_id<T : TypeTrait>() {
    let type_id = TypeTrait::type_id(None::<T>);
}

Problem

Suppose I have a rust trait that contains a function that does not take a &self parameter. Is there a way for me to call this function based on a generic type parameter of the concrete type that implements that trait? For example, in the get_type_id function below, how do I successfully call the type_id() function for the CustomType trait? ``` pub trait TypeTrait { fn type_id() -> u16; } pub struct CustomType { // fields... } impl TypeTrait for CustomType { fn type_id() -> u16 { 0 } } pub fn get_type_id<T : TypeTrait>() { // how? } ``` Thanks!

Original source