我有一个函数,其签名如下:
pub fn history<'a, I: IntoIterator<Item = &'a str>>(&self, _: I)
稍后,我有一个包含名为main
的字段的结构体,该字段是一个装箱的闭包。
main: box |args: &[&str], shell: &mut Shell| {
shell.history.history(args);
},
重要的是我使用了我展示签名的函数,并将
&[&str]
作为参数进行调用。我得到了以下编译错误:src/main.rs:281:47: 281:54 error: type mismatch resolving `<&[&str] as core::iter::IntoIterator>::Item == &str`:
expected &-ptr,
found str [E0271]
src/main.rs:281 shell.history.history(args);
显然,&[&str]
不能作为IntoIterator
使用。我尝试了shell.history.history(args.into_iter());
,但是收到了类似的错误信息。
奇怪的是,shell.history.history(args.iter().map(|s|*s));
可以工作。不过这似乎并不是正确的解决方案。
AsRef<str>
替代自定义的IntoStrSlice
吗? - Vladimir MatveevAsRef
可以这样使用!已编辑。 - Francis Gagnéwhere I::Item: AsRef<T>, T: Debug
(其中T
是第二个泛型类型),还是指where I::Item: AsRef<str> + Debug
? - Francis Gagné