Generic Traits functions

Consider:


struct Test {

}

impl Test {
    fn hello() -> String {
        "Hello".to_string()
    }
}

struct Foo<T> {
    bar: T
}

trait Something<T> {
    fn new() -> Foo<T>;
}

impl Something<Test> for Foo<Test> {
    fn new() -> Foo<Test> {
        Foo {
            bar: Test {}
        }
    }
}

impl<T> Foo<T> {
    fn blah(&self) {
        let x = &self.bar;        
        x.hello();
    }
}

fn main() {
   
}

⣿ Execution Close Standard Error Compiling playground v0.0.1 (/playground) error[E0599]: no method named hellofound for reference&Tin the current scope --> src/main.rs:31:11 | 31 | x.hello(); | ^^^^^ method not found in&T`

For more information about this error, try rustc --explain E0599.
error: could not compile playground due to previous error`

Is there a way around this?

hello() is not a method for Test object but it is a « class » method

you should declare hello(&self) instead

It's not clear to me what you're trying to accomplish. However, the only things that work with method syntax (variable.method()) are those that take a self receiver, like self or &self or &mut self [1]. The way you call an associated method without such a receiver is

TypeName::function()
// or
<TypeName as Trait>::function()

However, that won't work with the T in your code, because in a generic context, the only capabilities you can make use of [2] for the generic parameters are those which are declared available via a trait bound. There are no bounds [3] on the T in your impl<T> Foo<T> block. Moreover, even if there was one, it wouldn't matter here because hello is an associated function of the Test type, not of any trait. So T::hello() can never work either.

You could call Test::hello() directly, but it has nothing to do with T in that context.

Rust isn't like some languages where you can call x.hello() on anything at all and it will call it if it exists or throw a runtime error if it does not, or the like. Rust has to know it can make the call at compile time.


  1. or a handful of more rare ones also mentioning self ↩︎

  2. the only functions or methods you can call, for example ↩︎

  3. other than an implied Sized bound ↩︎

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.