I've been struggling to understand why the following code behaves the way it does (Playground):
use std::collections::HashMap;
trait Trait<'a> {
fn get_enum(&'a self) -> Enum<'a>;
}
#[derive(Clone)]
enum Enum<'a> {
Arr(Vec<&'a dyn Trait<'a>>),
Map(HashMap<String, &'a dyn Trait<'a>>)
}
impl<'a> Trait<'a> for Enum<'a> {
fn get_enum(&'a self) -> Enum<'a> {
self.clone()
}
}
fn process<'a>(val: &'a dyn Trait<'a>) -> Vec<&'a dyn Trait<'a>> {
let mut traits: Vec<&dyn Trait> = vec![];
match val.get_enum() {
Enum::Arr(v) => {
for elem in v {
traits.push(elem);
}
},
Enum::Map(m) => {
for elem in m.values() {
traits.push(elem);
}
}
}
traits
}
This throws the error:
error[E0277]: the trait bound `&dyn Trait<'_>: Trait<'_>` is not satisfied
--> src/main.rs:29:29
|
29 | traits.push(elem);
| ^^^^ the trait `Trait<'_>` is not implemented for `&dyn Trait<'_>`
|
= note: required for the cast to the object type `dyn Trait<'_>`
The thing that's strange to me isn't exactly the error as much as the fact that the error only shows up listing values from the HashMap
and not from Vec
's iterator. Can someone explain to me:
- Why the two structures' iterators behave so differently
- How I can pass values from my map into my array
I have found the same phenomenon occurs retrieving any value via the get
call as well.