Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust invoke trait method on generic type parameter

Tags:

rust

traits

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!

like image 867
LorenVS Avatar asked Dec 03 '13 03:12

LorenVS


People also ask

How do you implement a trait in Rust?

Implementing a trait in Rust To implement a trait, declare an impl block for the type you want to implement the trait for. The syntax is impl <trait> for <type> . You'll need to implement all the methods that don't have default implementations.

What does Dyn mean in Rust?

dyn is a prefix of a trait object's type. The dyn keyword is used to highlight that calls to methods on the associated Trait are dynamically dispatched. To use the trait this way, it must be 'object safe'. Unlike generic parameters or impl Trait , the compiler does not know the concrete type that is being passed.

Are Rust traits interfaces?

Rust is not an object oriented language. And traits are not exactly interfaces.

Can traits have fields Rust?

Traits can't have fields. If you want to provide access to a field from a trait, you need to define a method in that trait (like, say, get_blah ).


1 Answers

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>);
}
like image 143
sfackler Avatar answered Oct 06 '22 05:10

sfackler