こんな感じでやる。
成果物
参考
前回からの続き
テスト駆動(TDD)
- 失敗するテストを書き、想定通りの理由で失敗することを確かめる
- 十分な量のコードを書くか変更して新しいテストを通過するようにする
- 追加または変更したばかりのコードをリファクタリングし、テストが通り続けることを確認する
- 手順1から繰り返す
1. 失敗するテストを書く
src/lib.rs
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { vec![] } #[cfg(test)] mod test { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three."; assert_eq!( vec!["safe, fast, productive."], search(query, contents) ); } }
$ cargo test ... ---- test::one_result stdout ---- thread 'test::one_result' panicked at 'assertion failed: `(left == right)` left: `["safe, fast, productive."]`, right: `[]`', src/lib.rs:39:9
2. 成功するコードを書く
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { for line in contents.lines() { // 行に対して何かする } }
str.lines()
で改行ごとに分解する
各行を検索する
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { for line in contents.lines() { if line.contains(query) { // 行に対して何かする } } }
str.containts()
で指定した文字列が含まれているか判定する
合致した行を保存する
pub fn search<'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 }
contents
にquery
が含まれているなら、その行テキストをVectorに追加する。
戻り値について。Vec自体は所有権をムーブしている。Vec中身のstr
は引数contents
の一部である。それは参照であるためライフタイムの指定が必要。ライフタイム省略規則だけでは特定できないため、ライフタイム指定子により指定する必要がある。Vec中身のstr
は引数contents
の一部なので、ライフタイムも同じである。それをライフタイム指定子によって指定する。すなわち'a
。
テスト実行
成功。
$ cargo test Compiling minigrep v0.1.0 (/tmp/work/Rust.Minigrep.TDD.20190701120916/src/1/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 5.68s Running /tmp/work/Rust.Minigrep.TDD.20190701120916/src/1/minigrep/target/debug/deps/minigrep-59cba27a4e3f1289 running 1 test test test::one_result ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out Running /tmp/work/Rust.Minigrep.TDD.20190701120916/src/1/minigrep/target/debug/deps/minigrep-f69c65fea4d1414e running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out Doc-tests minigrep running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
run()
内でsearch()
を呼ぶ
pub fn run(config: Config) -> Result<(), Box<Error>> { let mut f = File::open(config.filename)?; let mut contents = String::new(); f.read_to_string(&mut contents)?; for line in search(&config.query, &contents) { println!("{}", line); } Ok(()) }
1件も合致しないとき。
$ cargo run AAA poem.txt Compiling minigrep v0.1.0 (/tmp/work/Rust.Minigrep.TDD.20190701120916/src/2/minigrep) ... query: AAA filename: poem.txt
いくつか合致するとき。
$ cargo run the poem.txt ... query: the filename: poem.txt Then there's a pair of us - don't tell! To tell your name the livelong day
$ cargo run body poem.txt ... query: body filename: poem.txt I'm nobody! Who are you? Are you nobody, too? How dreary to be somebody!
成功! これで指定した文字列に部分一致する行を抜き出すことができた。
対象環境
- Raspbierry pi 3 Model B+
- Raspbian stretch 9.0 2018-11-13
- bash 4.4.12(1)-release
- rustc 1.34.2 (6c2484dc3 2019-05-13)
- cargo 1.34.0 (6789d8a0a 2019-04-01)
$ uname -a Linux raspberrypi 4.19.42-v7+ #1219 SMP Tue May 14 21:20:58 BST 2019 armv7l GNU/Linux
前回まで
- Rustを学んでみたい(プログラミング言語)
- Rustの環境構築
- RustでHelloWorld
- Rustの和訳ドキュメント
- Cargoでプロジェクト作成・ビルド・実行
- クレートとは?
- Rustで関数を使ってみる
- Rustでモジュールを使ってみる
- Rustで乱数を生成する(rand)
- Rustで標準入力する(std::io::stdin().read_line())
- RustでMatch判定する(match)
- Rustでprintとread_lineを1行にする方法
- Rustで数当てゲーム
- クレート名にドット.が使えない
- Rustの変数と可変性(let, mut) error[E0384]: cannot assign twice to immutable variable
x
- Rustのimmutable束縛とconst定数の違い
- RustのREPL、evcxrのインストールに失敗した
- Rustでコンパイルするときの変数未使用warningを消す
- Rustの変数(再代入、再宣言(シャドーイング))
- Rustのシャドーイングについて
- イミュータブルについて(副作用)
- Rustの定数(const)
- Rustのデータ型(数値)
- Rustのデータ型(論理)
- Rustのデータ型(文字)
- Rustのデータ型(タプル)
- Rustのデータ型(配列)
- Rustの関数
- Rustのif式
- Rustのくりかえし文(loop)
- Rustのくりかえし文(while)
- Rustのくりかえし文(for)
- Rustの所有権(ムーブ)
- Rustの所有権(関数)
- Rustの所有権(スライス)
- Rustの構造体(定義とインスタンス化)
- Rustの構造体(プログラム例)
- Rustの構造体(メソッド)
- Rustの列挙型(enum)
- Rustの列挙型(enum)
- Rustの列挙型(enum)
- Rustのmatch(制御フロー演算子)
- RustでNULLを扱う(Option, Some, None)
- NULL参照は10億ドルの失敗だった
- Rustの列挙型に独自表示を実装する(E0277 対策 std::fmt::Display 実装)
- RustのIfLet(matchの糖衣構文)
- Rustのプロジェクト構造
- Rustのcargoでライブラリ&テスト(単体、結合)
- Rustのモジュール(mod)
- Rustのモジュール(pub)
- Rustのmod参照方法(
mod 子モジュール名;
,use 要素名;
,extern crate クレート名;
,super
) - Rustのインポートまとめ(Rust2018)
- RustのコレクションVec型
- RustのコレクションString型
- RustのコレクションHashMap型
- Rustのコレクション(練習問題)
- Rustのエラー処理
- Rustのジェネリクス
- Rustのトレイト
- Rustのライフタイム1
- Rustのライフタイム2(構造体の定義)
- Rustのライフタイム3(ライフタイム省略)
- Rustのライフタイム4(impl定義)
- Rustの静的ライフタイム5('static)
- Rustのライフタイム6(ジェネリクス、トレイト境界とともに)
- Rustのテストコードを書く
- Rustのテスト実行
- Rustのテスト体系化
- Rustでコマンドライン引数を受け取る
- Rustのファイル読込
- Rustでリファクタリング(モジュール性とエラー処理の向上)