How could I list traits a type had implemented?

Is there some way to find out all trait a type implemented? like Copy, Default, Into, AsRef.... thanks

Rustdoc displays trait implementations.

cargo doc --open

If it's your type, it has to be in a library (used via lib.rs, not in main.rs) and you may need to add --document-private-items.

thanks, of course I can check the doc, but I more want a kind of programming way to list some type's traits, if rust do have a way to do that, I can know and understand some type quickly.

No, you can't. Rust doesn't support reflection. You can emulate reflection with macros, but that won't work in this case.

1 Like

Reflection is just one of possible solutions. In this case OP just wants this for inspection (and not for runtime use). Therefore theoretically Rust or RLS or whatever may provide such an API but I'm not sure if there's one currently.

So, my answer still stands. You can't inspect elements at compile time or runtime beyond the capabilities of Any, but that is useless for figuring out what traits are implemented for a type. You could parse all of the source files (like RLS or rust-analyzer) but that is a lot of work, and doesn't seem like what the OP wanted.

You could potentially use the same mechanism rustdoc uses to get this data, and then, present it in a form other than HTML. That's all I'd be asking for if I were they, and its a common sort of thing I'd have a use for.

2 Likes

OK, thanks, seems only follow the doc or sourcecode is the way to go. But as you know, not like C++ or Jave, it's more easy to find some class or some type's "trait", you can check the source code, follow the implement code or extend code, that they are more specific, but in rust, you can impl here a trait for your type, impl somewhere for other trait, you will find the type traits come from everywhere. Any way, maybe I am very new in rust, and I believe trait very basic for rust, I just want to make clear for types I met. Thanks.

If you don't need the list of traits as a form of documentation, but you need to retrieve them programmatically, then what is the problem you are trying to solve? It seems to me that you are indeed looking for something related to reflection – are you looking for downcasting, or runtime type checking, or dynamic dispatch, or…?

1 Like

Hi, thanks, dynamic dispatch maybe more close. I don't know whether reflection is suitable for rust. As I know reflection will return a specific type information, but rust's trait may have many, not just std lib type, many trait type may from other external lib. Any way, I just start rust programming, and I find understand trait clearly very important to read rust source code, So I just ask if there is some way to help me list type traits. And now I should know there is no way to do that, all you can do is to remember every trait the std lib provide, then you can understand others lib's trait more clearly.

So you only want it as documentation, after all? What I don't understand is, what do you want to do with the traits once you obtained the list? Do you want to see if the type implements a trait and call one of its methods if so? Or something else? Or nothing?

I don't see why you want to list the traits programmatically. Yes, Rust uses traits extensively, but not in a reflection-based manner, rather, using generics or, less frequently, for dynamic dispatch. Neither approach solicits listing implemented traits programmatically.

2 Likes

Perhaps all the OP wants is a comprehensive listing of all the methods available for a type, clustered by trait. I suspect that many users (including me) would find that to be a useful way of exploring available Rust code not previously known to them.

5 Likes

Hi, I think I just from the starter view for better understand rust types. If I got the list, I should know how to use the type, the list can work as a cheatsheet. Like if you want to define a type, you should know how many traits should be implemented before it can work in the exists system. thanks

So, you want documentation? It doesn't sound like you want reflection based on this last comment. Rust already displays all implemented traits for a given type in the docs for that type, (even from blanket impls in the relevant section).

1 Like

You might be looking for an IDE with correct autocompletion, although unfortunately at the moment there is only IntelliJ IDEA and RLS and both I think are imperfect.

I think there are no way to list all traits (at compile time or runtime), but if you need to check whether type implements some trait, you can write Checker trait and use nightly specialization feature, example

Note that by using a macro, specialization is not required, thanks to the "autoref-based specialization" hack:

macro_rules! implements {(
    $T:ty : $($bounds:tt)*
) => ({
    use ::core::marker::PhantomData;

    trait DefaultValue {
        fn value (self: &'_ Self) -> bool { false }
    }
    impl<T : ?Sized> DefaultValue for &'_ PhantomData<T> {}
    trait SpecializedValue {
        fn value (self: &'_ Self) -> bool { true }
    }
    impl<T : ?Sized> SpecializedValue for PhantomData<T>
    where
        T : $($bounds)*
    {}
    (&PhantomData::<$T>).value()
})}

fn main ()
{
    use ::core::ops::Not;
    assert!(implements!(() : Copy)));
    assert!(implements!(String : Copy).not());
}
1 Like

thanks, it's fun to play with.

Thanks, very interesting to know. I thought compiler should rise an ambiguity error in such cases.

It doesn't because for a given T, there is a trait for T and a trait for &T, so there is no ambiguity.

On the other hand, note that the presented hack only works with concrete types, contrary to the full-featured specialization in nightly, so it is indeed "hackish"