Rust calls the trait method on a type parameter

Suppose I have a rust characteristic that contains a function that does not accept a self-diagnosis parameter. Is there a way to call this function based on a typical type parameter of a particular type that implements this trait? For example, in the get_type_id function below, how do I successfully call the type_id () function on the CustomType property?

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!

+6
source share
2 answers

As Autch noted, this is currently not possible. A workaround is to use a dummy parameter to indicate 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>); } 
+7
source

Unfortunately, this is currently not possible. This used to be based on implementation details, but it was eliminated in favor of, ultimately, implementing the proper way to do it.

When it is eventually implemented, it may look something like this: TypeTrait::<for T>::type_id() , however, there is currently no syntax installed in the stone.

This is a well-known case and one that is fully intended to support, it is simply regrettable that this is currently not possible.

A full discussion of this topic (the so-called related methods) is here: https://github.com/mozilla/rust/issues/6894 and here: https://github.com/mozilla/rust/issues/8888

+4
source

Source: https://habr.com/ru/post/959208/


All Articles