Suppose I have a struct like this
#[derive(Debug)]
pub struct QueryString<'buf> {
data: HashMap<Cow<'buf, str>, Value<'buf>>,
}
#[derive(Debug)]
pub enum Value<'buf> {
Single(Cow<'buf, str>),
Multiple(Vec<Cow<'buf, str>>),
}
How would I implement a function that returns an iterator over the values for a key?
impl<'buf> QueryString<'buf> {
pub fn get_ex(&'buf self, key: &str) -> Option<impl Iterator<Item = &'buf str>> {
/* ... */
}
}
I tried the following, but it does not compile:
impl<'buf> QueryString<'buf> {
pub fn get_ex(&'buf self, key: &str) -> Option<impl Iterator<Item = &'buf str>> {
match self.data.get(key) {
Some(value) => match value {
Value::Single(single) => Some(iter::once(single).map(Cow::as_ref)),
Value::Multiple(multiple) => Some(multiple.iter().map(Cow::as_ref)),
},
None => None
}
}
}
Error is:
mismatched types
--> server\src\http\query_string.rs:29:51
= note: expected struct `Map<std::iter::Once<&Cow<'_, str>>, for<'a> fn(&'a Cow<'_, str>) -> &'a str {<Cow<'_, str> as AsRef<str>>::as_ref}>`
found struct `Map<std::slice::Iter<'_, Cow<'_, str>>, for<'a> fn(&'a Cow<'_, str>) -> &'a str {<Cow<'_, str> as AsRef<str>>::as_ref}>`
So, it seems the problem is that the iterators are not the exactly same type.
But why would they have to be?
We only require the return type to implement the Iterator
trait, which they both do!
Is there any solution for this use case?
Thank you!