Creating an instance inside a generic struct function

Hello, I'm having a problem using generics.
I'm using a third party library that I can not change.
The library provides me with a trait LibraryTrait and function library_fn that takes a variable of any type with the trait LibraryTrait as a parameter.
So in:

library_fn(some_variable);

some_variable needs to have the trait LibraryTrait.

I want to implement a struct that can work with any type using the LibraryTrait as well, so I need to make it generic as well.
I implemented my own struct as such:

struct Test<T: LibraryTrait> {
}
impl <T> Test <T>
where T: LibraryTrait {
    fn some_function(&self) -> {
        library_fn(???);   
    }
}

As you can see, my problem is that I can not created instances from the generic trait in some_function.
As far as I know there is no way if creating dynamic instances from generics.
How can I bypass this if I can not make changes to the library?

You could require T to be LibraryTrait + Default. Then you can call simply call Default::default() to get an instance of T, if your return type is set to T. (or <T as Default>::default(), if you have to be explicit)

1 Like

LibraryTrait is implemented by an enum provided by the library.
So the given possible values for things I can pass to library_fn are enum values of that library.
This enum doesn't implement Default though.

If you're writing an application, you don't have to deal with generics just for the sake of using generics. Just use concrete types where you can. Your code will be easier to understand and maintain. Don't abstract eagerly! You can just deal with abstraction when you get to the point where it's necessary.

If you write a library, then users of the library can create their own type that implements Default and LibraryTrait. This includes creating a simple wrapper around the enum and delegating all the method calls to it.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.