현재 중복 된 일련의 반복 된 반복기 호출 (.lines().map(...).filter(...)
)을 캡슐화하는 함수를 작성하려고합니다. 컴파일 할 때 형식 서명을 알아낼 수 없습니다. Rust에 대해 이것이 불가능하거나 고도로 독창적이지 않다면, 나는 관용적 접근을위한 제안에 대해 개방적이다.반복자 체인의 추출 체인이 도우미 함수를 호출합니다.
use std::fs;
use std::io;
use std::io::prelude::*;
use std::iter;
const WORDS_PATH: &str = "/usr/share/dict/words";
fn is_short(word: &String) -> bool {
word.len() < 7
}
fn unwrap(result: Result<String, io::Error>) -> String {
result.unwrap()
}
fn main_works_but_code_dupe() {
let file = fs::File::open(WORDS_PATH).unwrap();
let reader = io::BufReader::new(&file);
let count = reader.lines().map(unwrap).filter(is_short).count();
println!("{:?}", count);
let mut reader = io::BufReader::new(&file);
reader.seek(io::SeekFrom::Start(0));
let sample_size = (0.05 * count as f32) as usize; // 5% sample
// This chain of iterator logic is duplicated
for line in reader.lines().map(unwrap).filter(is_short).take(sample_size) {
println!("{}", line);
}
}
fn short_lines<'a, T>
(reader: &'a T)
-> iter::Filter<std::iter::Map<std::io::Lines<T>, &FnMut(&str, bool)>, &FnMut(&str, bool)>
where T: io::BufRead
{
reader.lines().map(unwrap).filter(is_short)
}
fn main_dry() {
let file = fs::File::open(WORDS_PATH).unwrap();
let reader = io::BufReader::new(&file);
let count = short_lines(reader).count();
println!("{:?}", count);
// Would like to do this instead:
let mut reader = io::BufReader::new(&file);
reader.seek(io::SeekFrom::Start(0));
let sample_size = (0.05 * count as f32) as usize; // 5% sample
for line in short_lines(reader).take(sample_size) {
println!("{}", line);
}
}
fn main() {
main_works_but_code_dupe();
}
해결 방법은 체인 반복자의 형식 별칭을 사용하는 것입니다, 나는 생각한다. 나는 추상적 인 타입을 반환하는 것을 생각하지 않는다. (이 경우에는'short_lines'의 반복자를 반환 할 것이지만 여전히 녹슬지는 않습니다.)'impl Trait'에 대한 논의를 확인하십시오 (여기에는 추적 문제가 있습니다 : https : // github.com/rust-lang/rust/issues/34511) 야간 툴 체인을 사용하여 이미이 작업을 수행 할 수 있습니다. – bow