본문 바로가기

장 실습: 줄 번호와 함께 검색 결과 출력하기

클로저와 반복자를 연결해 검색 결과에 원래 줄 번호를 붙이고 기존 검색 결과도 유지합니다.

12장에서 배운 것을 모아 minigrep에 기능을 하나 더합니다. LINE_NUMBER 환경 변수가 설정되어 있으면, 일치한 줄 앞에 그 줄이 파일의 몇 번째 줄인지를 붙여 출력합니다. 줄을 고르는 조건은 클로저 글의 4번 문제에서처럼 클로저로 받습니다.

시작 상태

I/O 프로젝트 개선의 전체 파일로 minigrep을 준비하고, 반복자와 루프의 성능 비교에서 만든 비교 테스트까지 더한 상태로 시작합니다. src/main.rs는 그대로 두고 src/lib.rs를 고칩니다. poem.txt는 Cargo.toml과 같은 폴더에 둡니다. 시작할 때 IGNORE_CASE와 LINE_NUMBER는 설정하지 않습니다.

poem.txt의 내용은 다음과 같습니다. 중간의 빈 줄도 그대로 둡니다.

poem.txt
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!

만들기와 확인

완성 조건은 다음과 같습니다.

  • src/lib.rs에 pub fn search_by<'a, F>(contents: &'a str, keep: F) -> Vec<(usize, &'a str)>를 더합니다. F는 &str을 받아 bool을 돌려주는 클로저이고, 반환값은 keep이 true를 돌려준 줄의 번호와 줄을 묶은 튜플의 벡터입니다. 줄 번호는 1부터 셉니다.
  • search_by의 본문은 for 루프와 가변 벡터 없이 반복자 체인 하나로 씁니다.
  • Config에 line_number: bool 필드를 더하고, IGNORE_CASE와 같은 방식으로 LINE_NUMBER 환경 변수가 설정되어 있는지를 넣습니다.
  • run은 search_by로 검색합니다. ignore_case에 따라 서로 다른 클로저를 넘기고, line_number가 true이면 번호:줄, 아니면 줄만 출력합니다.
  • search_by의 테스트를 하나 더합니다. 기존 테스트는 모두 그대로 통과해야 합니다.

힌트는 세 가지입니다. Iterator의 enumerate 어댑터는 원소를 (인덱스, 원소) 튜플로 바꿔 내놓으며, 인덱스는 0에서 시작하는 usize입니다. 클로저의 매개변수 자리에는 |(index, line)|처럼 튜플 패턴을 쓸 수 있고, 쓰지 않는 자리는 _로 둡니다. 그리고 반복자 글의 4번 문제에서 본 것처럼 filter의 클로저는 원소의 참조를 받으므로, 튜플 안의 줄은 &&str이 되어 *로 한 겹 벗겨야 keep에 넘길 수 있습니다.

체크포인트

단계확인할 결과
1단계: 줄 번호 선택 함수search_by가 Rust:와 Trust me.를 각각 1번과 4번으로 돌려주는 numbered 테스트가 통과합니다.
2단계: 기존 검색 유지환경 변수 없이 cargo run -- body poem.txt를 실행하면 번호 없는 세 줄이 나옵니다.
3단계: 설정과 출력 연결LINE_NUMBER를 설정하면 같은 세 줄 앞에 1, 2, 6이 붙습니다. 확인 뒤 설정을 지웁니다.

다를 때 먼저 볼 곳

증상먼저 볼 곳
줄 번호가 1, 2, 3이다enumerate를 일치한 줄만 고르는 filter보다 앞에서 호출했는지
번호가 붙지 않는다Config.line_number, 환경 변수 읽기, run의 분기를 차례로 확인합니다.
파일을 찾지 못한다poem.txt와 Cargo.toml이 같은 폴더에 있는지, 그 폴더에서 실행했는지

완성 파일

완성 파일 전체와 확인 결과

search_by는 enumerate로 번호를 붙이고, filter로 고르고, map으로 0부터 센 인덱스를 1부터 세는 줄 번호로 바꾼 뒤, collect로 모읍니다. 번호를 먼저 붙이고 나서 걸러야 걸러진 뒤에도 원래 파일의 줄 번호가 남습니다.

src/lib.rs (search_by)
pub fn search_by<'a, F>(contents: &'a str, keep: F) -> Vec<(usize, &'a str)>
where
    F: Fn(&str) -> bool,
{
    contents
        .lines()
        .enumerate()
        .filter(|(_, line)| keep(*line))
        .map(|(index, line)| (index + 1, line))
        .collect()
}

run에서는 두 갈래가 서로 다른 클로저를 넘깁니다. 클로저마다 타입이 다르지만 search_by가 돌려주는 타입은 어느 쪽이든 Vec<(usize, &str)>이므로 if 식의 두 갈래 타입이 맞습니다. 대소문자를 무시할 때는 검색어를 소문자로 바꾼 lower_query를, 구분할 때는 query를 클로저가 캡처합니다.

완성한 src/lib.rs 전체는 다음과 같습니다. src/main.rs는 바꾸지 않습니다. search_case_insensitive는 I/O 프로젝트 개선 글의 2번 문제에서 고친 모습으로 실었고, 같은 글의 3번 문제에서 더한 count_matches와 그 테스트가 있다면 그대로 두면 됩니다.

src/lib.rs
use std::env;
use std::error::Error;
use std::fs;

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
    pub line_number: bool,
}

impl Config {
    pub fn build(
        mut args: impl Iterator<Item = String>,
    ) -> Result<Config, &'static str> {
        args.next();

        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a query string"),
        };

        let file_path = match args.next() {
            Some(arg) => arg,
            None => return Err("Didn't get a file path"),
        };

        let ignore_case = env::var("IGNORE_CASE").is_ok();
        let line_number = env::var("LINE_NUMBER").is_ok();

        Ok(Config {
            query,
            file_path,
            ignore_case,
            line_number,
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;
    let query = config.query;

    let results = if config.ignore_case {
        let lower_query = query.to_lowercase();
        search_by(&contents, |line| line.to_lowercase().contains(&lower_query))
    } else {
        search_by(&contents, |line| line.contains(&query))
    };

    for (number, line) in results {
        if config.line_number {
            println!("{number}:{line}");
        } else {
            println!("{line}");
        }
    }

    Ok(())
}

pub fn search_by<'a, F>(contents: &'a str, keep: F) -> Vec<(usize, &'a str)>
where
    F: Fn(&str) -> bool,
{
    contents
        .lines()
        .enumerate()
        .filter(|(_, line)| keep(*line))
        .map(|(index, line)| (index + 1, line))
        .collect()
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
        .lines()
        .filter(|line| line.contains(query))
        .collect()
}

pub fn search_case_insensitive<'a>(
    query: &str,
    contents: &'a str,
) -> Vec<&'a str> {
    let query = query.to_lowercase();

    contents
        .lines()
        .filter(|line| line.to_lowercase().contains(&query))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }

    fn search_loop<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
        let mut results = Vec::new();

        for line in contents.lines() {
            if line.contains(query) {
                results.push(line);
            }
        }

        results
    }

    #[test]
    fn loop_and_iterator_agree() {
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        for query in ["duct", "t", "monomorphization"] {
            assert_eq!(search_loop(query, contents), search(query, contents));
        }
    }

    #[test]
    fn numbered() {
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec![(1, "Rust:"), (4, "Trust me.")],
            search_by(contents, |line| line.to_lowercase().contains("rust"))
        );
    }
}

확인은 세 단계로 합니다. 먼저 cargo test에서 numbered를 포함한 모든 테스트가 통과해야 합니다. 다음으로 환경 변수 없이 cargo run -- body poem.txt를 실행해, 기존 검색 결과와 똑같이 세 줄이 번호 없이 나오는지 봅니다. 마지막으로 LINE_NUMBER를 설정하고 실행합니다. macOS와 Linux의 셸에서는 LINE_NUMBER=1 cargo run -- body poem.txt, PowerShell에서는 $Env:LINE_NUMBER=1; cargo run -- body poem.txt입니다.

1:I'm nobody! Who are you?
2:Are you nobody, too?
6:How dreary to be somebody!

poem.txt의 다섯째 줄은 빈 줄이고 lines는 빈 줄도 한 줄로 세므로, How dreary to be somebody!는 6번입니다. PowerShell에서는 확인이 끝난 뒤 Remove-Item Env:LINE_NUMBER로 설정을 지웁니다.

이 과제에는 12장의 내용이 모두 들어 있습니다. search_by는 여러 번 부를 클로저를 Fn 바운드로 받고, run이 넘기는 두 클로저는 환경의 query와 lower_query를 불변 참조로 캡처합니다. 본문은 어댑터 셋과 소비 어댑터 하나를 이은 게으른 체인이며, collect가 요청할 때 비로소 줄을 하나씩 처리합니다.

src/main.rs는 반복자를 받도록 고친 기존 파일을 그대로 사용합니다.

src/main.rs
use std::env;
use std::process;

use minigrep::Config;

fn main() {
    let config = Config::build(env::args()).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    if let Err(e) = minigrep::run(config) {
        eprintln!("Application error: {e}");
        process::exit(1);
    }
}

더 해 보기

  • search와 search_case_insensitive가 search_by를 불러 쓰도록 바꿉니다. 튜플에서 줄만 꺼내며, 기존 테스트가 계속 통과하는지 확인합니다.
  • IGNORE_CASE와 LINE_NUMBER를 함께 설정해 to를 검색합니다. 먼저 줄 번호를 손으로 구하고 2, 6, 8, 9번과 비교합니다. 확인 뒤 두 설정을 지웁니다.

이것으로 12장을 마칩니다. 다음 장의 릴리즈 프로필 설정부터는 Cargo와 crates.io의 기능을 더 살펴봅니다.