How to store any type


I want to do something in rust like the following:

struct S<T>;

struct Wrapper {
    s: S<any type>,

Obviously, rustc complains about it.
So my question is how to do it properly?

You may want to look into Box<Any>. Basically, all types implement the "Any" trait, and that trait is designed in such a way that you can make a boxed trait object out of it.

Thanks for reply.

Box<Any> does fulfill the requirement. However, I don't want anything other than S<T> stores in the wrapper. It should make rustc panic if I do that. Besides, I don't think I could use T in other contexts(other functions, etc.).

To enforce the requirement that the wrapper must store an S<T>, you can use an S<Box<Any>>. But that may not be quite what you want in your actual application. If you need T to implement any trait, you can use a more specialized boxed trait object like S<Box<Trait1 + Trait2>> instead. The only special thing that the Any trait brings to the table is the ability to downcast back to the original type T later on.

struct S<T>(pub T); 

struct Wrapper<U> {
   s: S<U>

This allows S(anything) and Wrapper{s: S(anything) }, where the type of anything is decided at compile time.

1 Like


I've already figured it out as something like S<T: Any> and Wrapper { s: Box<S: Any> } with specifying lifetime properly.

btw, I don't wan't make Wrapper as another generic type.