gpt4 book ai didi

rust - 从 &str 数组获取 Iterator

转载 作者:行者123 更新时间:2023-12-02 02:00:14 25 4
gpt4 key购买 nike

我正在尝试抽象一个函数来获取 std::str::Lines 的实例以及用于测试目的的模拟版本,由 &str 数组创建。

我的代码(确实有效)看起来像这样:

use std::fs;

#[test]
fn test_day_1() {
let v = ["3", "3", "4", "-2", "-4"].iter().map(|x| *x);
assert_eq!(day1(v), "334-2-4334-2-4");
}

fn day1_pre() -> String {
let contents = fs::read_to_string("day1.txt").expect("error reading file");
day1(contents.lines())
}

fn day1<'a>(lines: impl Iterator<Item = &'a str> + Clone) -> String {
lines
.map(|line| {
let v: Result<i32, _> = line.parse();
v.expect("could not parse line as integer")
})
.cycle()
.take(10)
.map(|x| x.to_string())
.collect()
}

但是,此代码之所以有效,是因为测试中存在奇怪的 .map(|x| *x) 。如果我删除它,我会收到以下错误:

error[E0271]: type mismatch resolving `<std::slice::Iter<'_, &str> as Iterator>::Item == &str`
--> src/lib.rs:6:16
|
6 | assert_eq!(day1(v), "334-2-4334-2-4");
| ^^^^ expected `str`, found `&str`
...
14 | fn day1<'a>(lines: impl Iterator<Item = &'a str> + Clone) -> String {
| -------------- required by this bound in `day1`
|
= note: expected reference `&str`
found reference `&&str`

我有点理解这个错误。 iter返回一个 &T,在本例中生成一个 &&str。我不明白的是为什么删除 map 并将 iter 替换为 into_iter (即 let v = ["3", "3", "4", "-2", "-4"].into_iter();) 也失败并出现相同的错误!

根据the documentationinto_iter 迭代 T,因此它应该在这里工作?

在写这篇文章时,我还尝试用 Vec 替换数组并使用 into_iter,最终结果是 let v = vec![ "3","3","4","-2","-4"].into_iter(); 结果成功了!然而,现在我更困惑了,为什么into_iter适用于Vec而不适用​​于Array

最佳答案

这是通过 Rust 1.53 release notes 宣布的。用于数组的 IntoIterator 是在 1.53 中实现的新功能,但在 2018 和 2021 版本中的行为有所不同:

This was not implemented before, due to backwards compatibility problems. Because IntoIterator was already implemented for references to arrays, array.into_iter() already compiled in earlier versions, resolving to (&array).into_iter().

As of this release, arrays implement IntoIterator with a small workaround to avoid breaking code. The compiler will continue to resolve array.into_iter() to (&array).into_iter(), as if the trait implementation does not exist. This only applies to the .into_iter() method call syntax, and does not affect any other syntax such as for e in [1, 2, 3], iter.zip([1, 2, 3]) or IntoIterator::into_iter([1, 2, 3]), which all compile fine.

Since this special case for .into_iter() is only required to avoid breaking existing code, it is removed in the new edition, Rust 2021, which will be released later this year. See the edition announcement for more information.

因此您的代码将 compile just fine使用 Rust 2021

关于rust - 从 &str 数组获取 Iterator<Item=str>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69076428/

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