Rust调用泛型类型参数的trait方法

Lor*_*nVS 7 traits rust

假设我有一个生锈特征,其中包含一个不带&self参数的函数.有没有办法让我根据实现该特征的具体类型的泛型类型参数调用此函数?例如,在下面的get_type_id函数中,如何成功调用CustomType特征的type_id()函数?

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?
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 7

正如Aatch所说,目前这还不可行.解决方法是使用虚拟参数指定以下类型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>);
}
Run Code Online (Sandbox Code Playgroud)