Check if generic type has trait (Downcasting?)

Given some generic type T, I want to inspect in some way if T has Trait and if so, perform checks on <T as Trait>::SomeAssociatedType, i.e. check the size with std::mem::size_of::<_>().

I've done some looking around and while I've found good content on downcasting, none of them seem to fit my need. Most notable, most of them involve trait objects, which I don't necessarily need here.

This playground is a minimum example of what I want to do, see the check_stuff function and the rest should be clear.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=03c5e0698e6cdaad28cc2431eee94b7e

Also, note that in this example I am passing an instance of Struct to the function as well, but in reality that should not be needed. All of the inspections that I want to do are on the associated types of <Struct as SomeTrait>, so no need for the instance.

Adding special behavior if a trait is implemented is called specialization, and is not possible without unstable features only available on nightly.

1 Like

From the RFC:

This RFC proposes a design for specialization , which permits multiple impl blocks to apply to the same type/trait, so long as one of the blocks is clearly "more specific" than the other. The more specific impl block is used in a case of overlap...

Indeed related, but not quite just. I do not care about the question of which impl to use. I care for just checking if it is implemented or not, without adding more trait bounds.

You can't check that. Rust doesn't have that level of dynamic behaviors. It doesn't keep track of such things at runtime.

You can only use traits when you know for sure ahead of time that the type has them. That's why Any is a trait itself.

1 Like

The closest thing I’ve come up with for this is defining a second trait, MaybeTrait over a wide class of objects:

trait MaybeTrait {
    const HAS_TRAIT:bool;
    fn as_trait(&self)->Option<&dyn Trait>;
}

You can’t define this correctly over all types without specialization, but it can still help if you’re dealing with only a well-defined subset of all types.

3 Likes

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.