我正在尝试抽象一个函数来获取两个实例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
with into_iter
(i.e. let v = ["3", "3", "4", "-2", "-4"].into_iter();
)也因同样的错误而失败!
根据文档, into_iter
迭代T
,因此它应该在这里工作?
在写这篇文章时,我还尝试用Vec
并使用into_iter
,这样最终的结果就是let v = vec!["3","3","4","-2","-4"].into_iter();
成功了!然而现在我更困惑了,为什么要into_iter
为。。。工作Vec
但不是为了Array
?