Rust invoke trait method on generic type parameter

前端 未结 2 1795
小鲜肉
小鲜肉 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 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) -> u16;
    }
    
    pub struct CustomType {
        // fields...
    }
    
    impl TypeTrait for CustomType {
        fn type_id(_: Option) -> u16 { 0 }
    }
    
    pub fn get_type_id() {
        let type_id = TypeTrait::type_id(None::);
    }
    

提交回复
热议问题