Calling a static method from a characteristic to a generic type

I have a trait with one function that does not take self as an argument:

 trait MyTrait { fn function(x: i32) -> i32; } struct Dummy; impl MyTrait for Dummy { fn function(x: i32) -> i32 { x * 2 } } fn call_method<T: MyTrait>(object: T) { let x = object.function(2); } fn main() {} 

A library user must implement a trait for any type, usually an empty structure. One of my functions accepts a generic type that implements MyTrait . When I try to call the function method on a generic type, it gives me this error:

error: no function method found for type T in the current scope

I tried the solution in answer to this question , but I get the same error. How can I call a static method for a generic type?

+5
source share
1 answer

When I try to call the function method on a generic type, ...

Two things: first of all, depending on how you want to look at it, function not a method. This is just a function that lives in the trait namespace (aka "related function").

Secondly, you are not trying to call function on a type, you are calling it on a value of that type. This is impossible, because, again, this is not a method; it does not have a self parameter.

The solution is to actually call the associated function function in the generic type, which looks like this:

 fn call_method<T: MyTrait>(object: T) { let x = T::function(2); } 

Sometimes this will not be specific enough. If you need to be more specific, you can also write above:

 fn call_method<T: MyTrait>(object: T) { let x = <T as MyTrait>::function(2); } 

The two are semantically identical; it is simply that the second is more specific and more likely to be resolved when you have a lot of traits.

+7
source

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


All Articles