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

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

问题描述:

假设我有一个 rust trait,它包含一个不接受 &self 参数的函数.有没有办法让我根据实现该特征的具体类型的泛型类型参数来调用此函数?比如下面的get_type_id函数中,如何成功调用CustomType trait的type_id()函数?

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?
}

谢谢!

正如 Aatch 提到的,这目前是不可能的.一种解决方法是使用一个虚拟参数来指定 Self 的类型:

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>);
}