How to convert concrete `T: Sized` to `Option<&dyn Trait>`

What I want is to return Some(&dyn Trait) when T: Trait + Sized and None otherwise. In my case I just want to 'enrich' debugging info in places where it is possible without placing any additional requirements to the outside code.

fn get_trait<T: Sized>(value: &T) -> Option<&dyn Debug> {
    // TODO
}

At first glance logically it should be possible to do in compile-time as compiler must know excact type and which traits it implements.

But is it possible in practice?

I don't think this is possible. Traits can only be used as compile-time constraints; there's no TraitId or anything comparable to Any which would make queries such as "does type T implement trait X" expressible either at compile-time or at runtime.

It would be possible via specialization, but that's still far away.

6 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.