第35回です。前回はこちら。
[第35回の様子]
2022/04/13に第35回を開催した。
内容としてはRust By Example 日本語版の「12. Cargo」、「12.1. Dependencies」、「12.2. Conventions」、「12.3. Tests」に取り組んだ。
参加者は6人ほど。
[学んだこと]
- 12.1. Dependencies
- まずはプロジェクト作成
$ cargo new foo
$ tree foo
foo
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
- 次に依存関係管理:cargo.tmlのdependencies欄に以下のように書く
[package] name = "foo" version = "0.1.0" edition = "2021" [dependencies] clap = "2.27.1" // CLI用のライブラリ
// オンラインのリポジトリから取得 rand = { git = "https://github.com/rust-lang-nursery/rand" } // ローカルのディレクトリから取得 bar = { path = "../bar" }
- Javaのmavenやgradleはルートディレクトリで実行するのが普通だが、cargoはプロジェクトのどのディレクトリでもビルドや実行ができるらしい。すごい
- 12.2. Conventions
- 同じプロジェクトで別のバイナリを作りたい時は以下のようにする
$ tree foo
foo
├── Cargo.toml
└── src
├── main.rs
└── bin // binディレクトリを追加
└── my_other_bin.rs // バイナリにしたい.rsファイル
- このバイナリをビルドするときは
cargo build --bin my_pther_binのようにする - 12.3. Tests
- Rustではユニットテストはモジュールのファイル内に記載する
- が、ここではそれとは別の結合テストの書き方を学ぶ
- 以下のようにtestsディレクトリを作って、そこに結合テストを配置する
$ tree foo foo ├── Cargo.toml ├── src │ └── main.rs │ └── lib.rs └── tests // ここに結合テスト ├── my_test.rs └── my_other_test.rs
cargo testコマンドで結合テストも実行できるcargo test (プレフィクス)で特定の名前で始まるテストのみ実行できる- cargoのテスト実行は並列なので、以下のようなテストは注意が必要
// 同じファイルにテキストを出力する2つのテスト
#[cfg(test)]
mod tests {
// Import the necessary modules
use std::fs::OpenOptions;
use std::io::Write;
// This test writes to a file
#[test]
fn test_file() {
// Opens the file ferris.txt or creates one if it doesn't exist.
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open("ferris.txt")
.expect("Failed to open ferris.txt");
// Print "Ferris" 5 times.
for _ in 0..5 {
file.write_all("Ferris\n".as_bytes())
.expect("Could not write to ferris.txt");
}
}
// This test tries to write to the same file
#[test]
fn test_file_also() {
// Opens the file ferris.txt or creates one if it doesn't exist.
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open("ferris.txt")
.expect("Failed to open ferris.txt");
// Print "Corro" 5 times.
for _ in 0..5 {
file.write_all("Corro\n".as_bytes())
.expect("Could not write to ferris.txt");
}
}
}
[まとめ]
モブプログラミングスタイルでRust dojoを開催した。
rustcだけで頑張っていた先週と比べて、cargoのおかげで楽に依存関係が管理できるようになった。便利〜。
今週のプルリクエストはこちら。