rusttrait-objects

Is there any way to use Associated Function of a trait in Rust?


I was experimenting with associated functions inside a trait's implementation, in order to use the trait's original implementation of the function. But I can't find a way to do that. My experimentation code :

pub trait T1 {
    // note: trait items always share the visibility of their methods.
    fn new() -> String {
        return String::new();
    }
}

pub enum X_type {
    String,
}

struct T1_1 {
    buddy: String,
}

impl T1 for T1_1 {}

fn main() {
    println!("{}", <dyn T1 as T1>::new());
}

Link to the playground.

I have tried tweaking the code here and there to see if T1::new() can be used, but it does not seem possible.


Solution

  • If you try T1::new() the compiler will actually tell you what to do:

    error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
      --> src/main.rs:19:20
       |
    3  | /     fn new() -> String {
    4  | |         return String::new();
    5  | |     }
       | |_____- `T1::new` defined here
    ...
    19 |       println!("{}", T1::new());
       |                      ^^^^^^^^^ cannot call associated function of trait
       |
    help: use the fully-qualified path to the only available implementation
       |
    19 |     println!("{}", <T1_1 as T1>::new());
       |                    ++++++++   +
    

    This is because there can be different implementation for T1::new() for each type which implements this trait, so you should specify which implementation you want.