Smartbit.オンライン書架

第2章: 環境構築

図2-1: rust error handling

2.1 rustupのインストール

Rustの標準的なインストール方法はrustupを使うことです。rustupはRustのバージョン管理ツールであり、複数のRustバージョンを簡単に切り替えられます。

Linux/macOSの場合:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

実行後、シェルを再起動するか、次のコマンドで環境変数を反映させます。

source $HOME/.cargo/env

Windowsの場合は、公式サイトからインストーラーをダウンロードしてください。

インストール確認:

rustc --version

![図2-2: rustcバージョン確認](images/term-01-rustc-version.png)

![図2-3: cargoバージョン確認](images/term-02-cargo-version.png)
rustup --version
cargo --version

2.2 Cargoの基礎

Cargoはプロジェクト管理とビルドツールです。依存パッケージの管理、テスト実行、ドキュメント生成など、Rustの開発に必要なすべての機能を提供します。

新規プロジェクト作成:

cargo new my_project
cd my_project

生成されるディレクトリ構造:

my_project/
├── Cargo.toml      # プロジェクト設定ファイル
└── src/
    └── main.rs     # エントリーポイント

Cargo.tomlの内容:

[package]
name = "my_project"
version = "0.1.0"
edition = "2021"

[dependencies]

プロジェクトのビルド:

cargo build           # デバッグビルド
cargo build --release # リリースビルド(最適化あり)

実行:

cargo run              # ビルドして実行
cargo run --release    # リリースビルドで実行

cargo run --release    # リリースビルドで実行

![図2-4: cargo newプロジェクト作成](images/term-03-cargo-new.png)

![図2-5: cargo buildコンパイル](images/term-04-cargo-build.png)

![図2-6: cargo run実行](images/term-05-cargo-run.png)

2.3 VSCodeとrust-analyzer

Visual Studio CodeでRustを効率的に書くには、rust-analyzer拡張が必須です。

  1. VSCodeを開く
  2. Extensions(Ctrl+Shift+X)で「rust-analyzer」を検索
  3. 公式のrust-analyzer拡張をインストール

設定(推奨):

settings.jsonに以下を追加します。

{
  "[rust]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "rust-lang.rust-analyzer"
  },
  "rust-analyzer.checkOnSave.command": "clippy

![図2-8: Clippyリントツール](images/term-10-clippy-output.png)"
}

これでコード保存時に自動フォーマットが行われ、clippy

図2-8: Clippyリントツールによるリント警告も表示されます。

2.4 開発環境の確認

それでは、開発環境が正しく整えられたか確認します。

cargo new environment_test
cd environment_test

src/main.rsを以下のように編集:

fn main() {
    let greeting = "環境構築完了!";
    println!("{}", greeting);

    let numbers: Vec<i32> = vec![1, 2, 3, 4, 5];
    for num in numbers.iter() {
        println!("数値: {}", num);
    }
}

実行:

cargo run

出力が表示されたら、環境構築は成功です。

図2-7: Cargoビルドパイプライン

ハンズオン:プロジェクトテンプレートの作成

複数のプロジェクトを作成するとき、テンプレートがあると便利です。新規プロジェクトを作成し、基本的なファイル構成を整えます。

cargo new template_project
cd template_project

以下のディレクトリ構造を作成:

mkdir tests
mkdir examples
mkdir benches

Cargo.tomlに設定を追加:

[package]
name = "template_project"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <you@example.com>"]
description = "A template Rust project"

[dependencies]

[dev-dependencies]

src/lib.rsを作成(ライブラリモード):

/// Hello 関数は、与えられた名前で挨拶します
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

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

    #[test]
    fn test_greet() {
        assert_eq!(greet("Rust"), "Hello, Rust!");
    }
}

まとめ

練習問題

  1. rustupを使ってRustの別のバージョンをインストールしてみなさい
  2. Cargo.tomlの各項目の意味を調べなさい
  3. 簡単なプロジェクトを作り、cargo test

図3-1: cargoテスト実行でテストを実行してみなさい