How to check if struct instance implemented marker trait

Hi, how do I check if my struct instance is implemented with marker trait but another struct instance does not, thanks

pub struct MyStruct;

pub struct AnotherStruct;

pub trait Common {
    fn common(&self)

impl Common for MyStruct {
    fn common(&self) {}

impl Common for AnotherStruct {
    fn common(&self) {}

pub trait IsDoable {}

impl IsDoable for MyStruct {}

let my: Box<dyn Common> = MyStruct{};
let a: Box<dyn Common> = AnotherStruct{};

// check my is implemented with IsDoable but a is not

First of all, you can't have a variable of type Common. You could have variable of type Box<Common>, if you're on the older edition, but this is deprecated in 2018 and AFAIK removed altogether in 2021 - you have to use Box<dyn Common>, if you actually mean this.

Second, when you cast some struct to the trait object, then all you can do with it is described by the trait, no exceptions. So if you really want to check for marker trait given only a dyn Common - you have to add some method on Common, and without specialization (which is not even close to being stabilized) this will not guarantee the correct answer.

Third, why do you try to use Common as a type in the first place, instead of the specific types?

1 Like

hi thanks for the input,

if I remove the Common trait and use below code, how do I check if IsDoable is implemented? thanks

let my  = MyStruct{};
let a = AnotherStruct{};

I believe they're asking why you need to check isDoable on the two types, rather than just doing something different for each type? In other words, what are you really trying to do at a higher level than you've described so far?

isDoable is defined in external crate, I choose to use that to differentiate struct instances if there is a way to check

There is not a way to check.

We can help you to find a different approach, if you can tell us the reason you want to check.

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.