Restricting Any trait to specif group of types

I have implemented a struct that can stored any data using the Any trait passed as parameters (storing) and returns (retrieving). All move actions, as storing takes ownership of the data. Everything works nicely and in the expected manner, downcasting to get the actual data back to manipulate.

However I would like to restrict the types of data that can be stored in the struct, perhaps by using a marker trait to tag the data, and thus only data that implements the marker trait is allowed to be stored in the struct. I could make the marker trait extend the Any trait, though run into the issue of downcasting when retrieving the data from the struct to obtain the actual data type that implements the marker. That is the downcast is not supported for the data marker trait, even though data marker extends the Any trait.

So makes me wonder.

Is it possible to restrict the types allowed for Any trait using a marker trait, or some other means? And still be able to downcast to the actual data type, to manipulate the fields (or by methods) of the data type, by code that knows of the data type in question.

You can make your own trait, and require it instead.

If you still need Any functionality, then

pub trait MyLimitedTrait: Any {}

will require every type implementing MyLimitedTrait to also implement Any.

If you don't want 3rd party code adding implementations of MyLimitedTrait for new types, see "sealed traits".

1 Like

Thinking about restricting Any trait the last few days. I decided not to restrict, but rather let the user of the storage to manage what types goes in. Keeping the storage as simple as possible.

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.