Hi, I'm trying to define a trait, that includes an option to create it self, and do an operation, to then use all structs that implements the trait with their respective functions:
But I know this is not allowed.... a safe Trait can not use Self as a return value.... but how can I achieve something similar? have the trait it self as return with dyn is also not allowed....
Your code in the Playground can be fixed by restricting the default() method to non-trait-objects, using the where Self: Sized clause on the method. That'll allow you to create an instance of the type as long as it's not a trait object.
If you want a default value for the concrete typeBox<dyn Stat>, then you'll have to supply a specific type to serve as the underlying, statically-typed value. You can do that by adding an impl block to dyn Stat, just like you would do with any other type that you created.
Hi, there is some issues with the solution, impl in the Trait, you are using the struct Adder to construct the default value, while it should be Self, only that changes causes a lot of things to be handled that I still don't know very well how to do it.
Each Struct need to have its own way to foo and default.
There's no such thing as conjuring a dyn Trait from thin air, without an underlying concrete type. It just doesn't make any sense. A dyn Traitmust be coerced from a static type that implements the trait. This is exactly what I was explaining in my previous post.
All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable:
...
Explicitly non-dispatchable functions require:
Have a where Self: Sized bound (receiver type of Self (i.e. self) implies this).
So by adding where Self: Sized you can create a trait object for the trait, but the trait object will not allow calling that one method. That method can still be called for a regular (not dyn) implementation of the trait.