我有一个具有以下签名的函数:
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));确实起作用。然而,这似乎并不是正确的解决办法。
发布于 2016-02-02 03:24:56
让我们来看看 is implemented for slices
impl<'a, T> IntoIterator for &'a [T]
type Item = &'a T
type IntoIter = Iter<'a, T>
fn into_iter(self) -> Iter<'a, T>注意,Item被定义为对T的引用,其中T是片中项的类型。因为您有&str的一部分,这意味着Item是&&str。
您可以使用.map(|s| *s),正如您所尝试的那样,取消外部引用并生成一个&str迭代器。
另一种解决方案是将history函数概括为同时接受I: IntoIterator<Item = &'a str>和I: IntoIterator<Item = &'b &'a str>。为了做到这一点,我们需要一个&'a str和&'b &'a str都实现的特性。为此,我们可以使用AsRef (感谢Vladimir Matveev指出这一点):
pub fn history<I>(i: I)
where
I: IntoIterator,
I::Item: AsRef<str>,
{
for s in i {
println!("{}", s.as_ref());
}
}
fn main() {
history(&["s"]);
}https://stackoverflow.com/questions/35144386
复制相似问题