pub trait Store {
fn query_valid_paths(&mut self, paths: &mut dyn Iterator<Item = &str>) -> Vec<String>;
}
不幸的是,它并不完美:
It works out of the box only for iterators of
&str
; for iterators ofString
, e.g.Vec<String>
, I have to call it with the following magicmap
incantation, which is really ugly, and I'd never invent it as a newbie without help:// `vec` is a std::vec::Vec<String> store.query_valid_paths(&mut vec.iter().map(|s| &**s));
It takes an
Iterator
, but I'd love if I could take anIntoIterator
. In other words, I'd like to be able to call it just like this:store.query_valid_paths(&vec);
可能吗?
失败尝试1
基于一个更简单的关于函数接受字符串迭代器的问题,我想像这样的方式可能会起作用:
pub trait Store {
fn query_valid_paths<S>(&mut self, paths: impl IntoIterator<Item = S>) -> Vec<String>
where
S: AsRef<str>;
}
但是这似乎使它成为一个“通用方法”,触发静态分派...
第二次尝试失败
我在 Rust Discord 上得到了另一个建议,具体来说:
pub trait Store {
fn query_valid_paths_inner(&mut self, paths: &mut dyn Iterator<Item = &str>) -> Vec<String>;
}
impl dyn Store {
pub fn query_valid_paths<'a>(&mut self, paths: impl IntoIterator<Item = &'a str>) -> Vec<String> {
let mut it = paths.into_iter();
self.query_valid_paths_inner(&mut it)
}
}
但是当我尝试将
AsRef<str>
添加到它时,我遇到了生命周期错误,并且似乎无法使它适用于String
和&str
迭代器...