gpt4 book ai didi

rust - 将切片作为 IntoIterator 传递

转载 作者:行者123 更新时间:2023-11-29 07:59:52 25 4
gpt4 key购买 nike

我有一个具有以下签名的函数:

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)); 确实有效。不过,这似乎不是正确的解决方案。

最佳答案

我们来看看how IntoIterator 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<str> 为此(感谢 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"]);
}

关于rust - 将切片作为 IntoIterator 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com