Rust invoke trait method on generic type parameter

前端 未结 2 1794
小鲜肉
小鲜肉 2021-01-12 04:29

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

相关标签:
2条回答
  • 2021-01-12 04:48

    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

    0 讨论(0)
  • 2021-01-12 05:07

    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>);
    }
    
    0 讨论(0)
提交回复
热议问题