I'm working with dynamic types and need to filter a Vec<Box<Any>>
to ensure that each type can only appear once. This is what I tried:
use std::any::Any;
pub fn dedup_types(mut list: Vec<Box<Any>>) -> Vec<Box<Any>> {
list.sort_unstable_by_key(|elem| elem.type_id());
list.dedup_by_key(|elem| elem.type_id());
list
}
but it fails with this error:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/lib.rs:5:35
|
5 | list.dedup_by_key(|elem| elem.type_id());
| ^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 5:23...
--> src/lib.rs:5:23
|
5 | list.dedup_by_key(|elem| elem.type_id());
| ^^^^^^^^^^^^^^^^^^^^^
= note: ...so that the types are compatible:
expected &&mut std::boxed::Box<(dyn std::any::Any + 'static)>
found &&mut std::boxed::Box<(dyn std::any::Any + 'static)>
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `&mut std::boxed::Box<(dyn std::any::Any + 'static)>` will meet its required lifetime bounds
--> src/lib.rs:5:35
|
5 | list.dedup_by_key(|elem| elem.type_id());
| ^^^^^^^
I'm not sure what this error means (the "expected" and "found" types are exactly the same) or why dedup_by_key
fails when sort_unstable_by_key
succeeds with exactly the same key extraction function. Any ideas?