Rust invoke trait method on generic type parameter

浪子不回头ぞ 提交于 2019-12-01 01:18:45

问题


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!


回答1:


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



回答2:


Unfortunately, this isn't currently possible. It used to be, based on a implementation detail, however that was removed in favor of eventually implementing a proper way of doing this.

When it is eventually implemented, it may end up looking something like this: TypeTrait::<for T>::type_id(), however there is, currently, no syntax set in stone.

This is a known case and one that is fully intended to be supported, it is just unfortunate that it currently is not possible.

The full discussion about this topic (called associated methods) is here: https://github.com/mozilla/rust/issues/6894 and here: https://github.com/mozilla/rust/issues/8888



来源:https://stackoverflow.com/questions/20342436/rust-invoke-trait-method-on-generic-type-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!