Trait with generic container return type

I have this trait:

pub trait S<T>{
    fn s(&self) -> Box<dyn S<T>>;

but what if I want it to be thread safe sometimes and sometimes not?

I want to be generic on the container that has the return type:

pub trait S<T, Container>{
    fn s(&self) -> Container<dyn S<T>>;

is there a way to do it?
but I get

   Compiling playground v0.0.1 (/playground)
error[E0109]: type arguments are not allowed for this type
 --> src/
2 |     fn s(&self) -> Container<dyn S<T>>;
  |                              ^^^^^^^^ type argument not allowed

For more information about this error, try `rustc --explain E0109`.

Which containers would you like to be generic over?

Box and Arc and sometimes Arc<Mutex<>>

How do you plan to use this trait in context? I'm having trouble understanding why you would want the implementor of the trait to decide whether to return Box<...> or Arc<...> or etc., and why this function needs to be part of a trait at all.

To elaborate a bit: it seems strange to have a generic trait with a method whose return type is a boxed trait object for the same trait. I think that's probably not the design you want to solve whatever problem you're facing, and hopefully with some more context we can figure out a better design.

To address the original question, Rust's unstable support for generic associated types does target this kind of thing, but currently traits with GATs are not object safe.

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.