Rust 对泛型类型参数调用 trait 方法 [英] Rust invoke trait method on generic type parameter

查看:32
本文介绍了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>);
}

这篇关于Rust 对泛型类型参数调用 trait 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆