Can't call a generic implinentation in a trait

Hello, I have a default implementation of a certain method in the trait, which I want to be able to call.

trait TraitA {
    fn new() -> impl TraitA {
        StructA {}
    }
}

struct StructA;
impl TraitA for StructA {}

fn main() {
    let struct_a = TraitA::new();
}

The issue is arising from the fact that I need to specify a specific implementation of TraitA for example <StructA as TraitA> however StructA might possibly overwrite the default new implementation in TraitA. So I'm wondering about how should I properly write this code?

There's no way to call the default method body specifically, you have to call the method of some implementation. You can create a dedicated implementing type for this purpose of needed.

1 Like

I would say the most proper thing to do is to not make this an associated function. Functions related to a trait which return specific implementations of a trait should be free functions in the relevant module, instead. (The standard library follows this; for example, std::iter::repeat() and std::future::ready().)

4 Likes