When I tried to transfer the Jave example given by Head First Design to Rust codes, a weird "type mismatch" error occurred.
This seems easy to solve but, after my doublecheck, I still cannot figure out why the error occurred and how to solve it. Can someone be so kind as to help me out? THANKS!
Codes related are below:
pub type DynMenuIter = Box<dyn Iterator<Item=Box<dyn MenuComponent>>>;
pub struct CompositeIterator{
stack: Vec<DynMenuIter>
}
impl CompositeIterator{
pub fn new(iter: DynMenuIter) > Self{
let mut stack = Vec::new();
stack.push(iter);
CompositeIterator { stack }
}
}
pub trait MenuComponent{
fn get_iter(&mut self) > Option<DynMenuIter>;
// some other methods
}
pub struct Menu{
name: String,
description: String,
menu_components: HashSet<Box<dyn MenuComponent>>
}
impl MenuComponent for Menu{
fn get_iter(&mut self) > Option<DynMenuIter>{
// error occurred here when newing a CompositeIterator
let composite_iter = CompositeIterator::new(Box::new(self.menu_components.iter()));
Some(Box::new(composite_iter))
}
}
And the error is below:
error[E0271]: type mismatch resolving `<std::collections::hash_set::Iter<'_, std::boxed::Box<dyn composite_pattern::backbone::MenuComponent>> as std::iter::Iterator>::Item == std::boxed::Box<dyn composite_pattern::backbone::MenuComponent>`
> src\composite_pattern\backbone.rs:113:53

113  let composite_iter = CompositeIterator::new(Box::new(self.menu_components.iter()));
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected reference, found struct `std::boxed::Box`

= note: expected type `&std::boxed::Box<dyn composite_pattern::backbone::MenuComponent>`
found type `std::boxed::Box<dyn composite_pattern::backbone::MenuComponent>`
= note: required for the cast to the object type `dyn std::iter::Iterator<Item = std::boxed::Box<dyn composite_pattern::backbone::MenuComponent>>`
I am totally comfused by the first note, and I don't know why a reference is expected since I coded pub fn new(iter: DynMenuIter) > Self
for CompositeIterator
.
I think these codes above are related to the error, but if you cannot understand what these codes do, please let me know or refer to source codes (https://github.com/ifsheldon/RustyOOPatterns/tree/master/src/composite_pattern) uploaded to Github on my repo.