Implement trait for a dynamic field

I have the following struct:

struct MyStruct {
    id: i32,
    dyn_field: Option<Arc<dyn Any + Sync + Send>>,

and I would like to implement a trait, say PartialEq for it. Obviously, just adding #[derive(PartialEq)] will not work because the compiler will complain that dyn_field does not implement PartialEq. Is such a thing possible or am I overlooking something here?

You'll have to use a trait that ensures convertibiloty to Any and has PartialEq as a supertrait bound. You can roll your own, or use eg. my dyn_ord::DynEq trait.


depending what's your semantic for two MyStruct to be equal. e.g. if you just want to compare whether two Arcs are pointing to the same object (i.e. memory address as identity, search "value semantics" vs "reference semantics"), you can use Arc::ptr_eq():


Here's a walkthrough on rolling your own.

1 Like

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.