I'm trying to create a map where the keys are trait objects.
structs
which impl
the trait have all derived Ord, Eq etc. In my case, this is simple as the internal fields are all integers and strings.
My attempt so far has been to define a trait as below, but the compiler says that Ord is not satisfied.
I'm not sure how to tell the compiler that the concrete structs which I intend to add to the map always do satisfy Ord bounds.
use std::collections::BTreeMap;
trait EntityAPI {}
#[derive(Hash, Eq, PartialEq, Debug, Ord, PartialOrd)]
struct Entity1 {
id: u8,
name: String,
}
impl EntityAPI for Entity1 {}
#[derive(Hash, Eq, PartialEq, Debug, Ord, PartialOrd)]
struct Entity2 {
id: u8,
name: String,
}
impl EntityAPI for Entity2 {}
pub fn main() {
let e1 = Entity1{id: 1, name: String::from("e1")};
let e2 = Entity2{id: 2, name: String::from("e2")};
let mut map: BTreeMap<Box<dyn EntityAPI>, f64> = BTreeMap::new();
map.insert(e1, 11.0);
map.insert(e2, 22.0);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0599]: no method named `insert` found for type `std::collections::BTreeMap<std::boxed::Box<dyn EntityAPI>, f64>` in the current scope
--> src/main.rs:25:9
|
25 | map.insert(e1, 11.0);
| ^^^^^^ method not found in `std::collections::BTreeMap<std::boxed::Box<dyn EntityAPI>, f64>`
|
= note: the method `insert` exists but the following trait bounds were not satisfied:
`std::boxed::Box<dyn EntityAPI> : std::cmp::Ord`
error[E0277]: the trait bound `dyn EntityAPI: std::cmp::Ord` is not satisfied
--> src/main.rs:24:54
|
24 | let mut map: BTreeMap<Box<dyn EntityAPI>, f64> = BTreeMap::new();
| ^^^^^^^^^^^^^ the trait `std::cmp::Ord` is not implemented for `dyn EntityAPI`
|
= note: required because of the requirements on the impl of `std::cmp::Ord` for `std::boxed::Box<dyn EntityAPI>`
= note: required by `std::collections::BTreeMap::<K, V>::new`
error[E0599]: no method named `insert` found for type `std::collections::BTreeMap<std::boxed::Box<dyn EntityAPI>, f64>` in the current scope
--> src/main.rs:26:9
|
26 | map.insert(e2, 22.0);
| ^^^^^^ method not found in `std::collections::BTreeMap<std::boxed::Box<dyn EntityAPI>, f64>`
|
= note: the method `insert` exists but the following trait bounds were not satisfied:
`std::boxed::Box<dyn EntityAPI> : std::cmp::Ord`
error: aborting due to 3 previous errors
Some errors have detailed explanations: E0277, E0599.
For more information about an error, try `rustc --explain E0277`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.