【发布时间】:2021-09-06 14:46:32
【问题描述】:
我正在尝试抽象一个函数来获取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 并用into_iter(即let v = ["3", "3", "4", "-2", "-4"].into_iter();)替换iter 也会失败并出现同样的错误!
根据the documentation,into_iter 迭代T,因此它应该在这里工作?
在写这篇文章时,我还尝试用Vec 替换数组并使用into_iter,这样最终的结果就是let v = vec!["3","3","4","-2","-4"].into_iter();,并且成功了!但是,现在我更困惑了,为什么into_iter 可以为Vec 工作,而不能为Array 工作?
【问题讨论】:
-
it's complicated 现在改用
copied()或cloned()