简体   繁体   English

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

[英]Rust invoke trait method on generic type parameter

Suppose I have a rust trait that contains a function that does not take a &self parameter. 假设我有一个生锈特征,其中包含一个不带&self参数的函数。 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? 例如,在下面的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?
}

Thanks! 谢谢!

As Aatch mentioned, this isn't currently possible. 正如Aatch所说,目前这还不可行。 A workaround is to use a dummy parameter to specify the type of Self : 解决方法是使用虚拟参数指定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>);
}

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. 当它最终实现时,它可能最终看起来像这样: TypeTrait::<for T>::type_id() ,但是目前没有语法设置。

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//github.com/mozilla/rust/issues/6894和这里: https//github.com/mozilla/rust/issues/8888

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM