Cargo

パッケージマネージャーRustビルドシステムCrates.ioワークスペースEdition 2024統合ツールチェーン

パッケージマネージャー

Cargo

概要

Cargoは、Rustプログラミング言語の公式パッケージマネージャー兼ビルドシステムで、依存関係管理、プロジェクト構築、テスト実行、パッケージ公開を統合的に行います。Cargo.tomlファイルによるプロジェクト設定、crates.ioエコシステムとの統合、ワークスペース機能による大規模プロジェクト管理を提供します。2024年にリリースされたCargo 2.0では、ビルド速度の大幅改善、スマートな依存関係処理、新しいコマンド群による開発ワークフローの簡素化が実現されています。Rust Edition 2024サポートにより、最新の言語機能と完全に統合された開発体験を提供します。

詳細

Cargoは2014年にRustプロジェクトの一部として開発され、言語とパッケージマネージャーの密接な統合を実現しました。Cargo.tomlファイルでプロジェクトメタデータと依存関係を管理し、Cargo.lockファイルで正確なバージョンを固定して再現可能なビルドを保証します。Crates.ioはRustの中央パッケージリポジトリとして機能し、オープンソースライブラリの配布を担います。ワークスペース機能により、複数の関連クレートを単一のプロジェクト内で効率的に管理できます。ビルドスクリプト、カスタムターゲット、条件付きコンパイルなどの高度な機能により、システムプログラミングからWebアプリケーションまで幅広い用途に対応します。Edition 2024サポートにより、最新のRust言語機能との完全な互換性を提供しています。

メリット・デメリット

メリット

  • 統合ツールチェーン: パッケージ管理、ビルド、テスト、公開を一つのツールで統合
  • ゼロ設定: 新規プロジェクトですぐに使える標準的な設定
  • 高速ビルド: 増分コンパイルと並列ビルドによる高速化
  • ワークスペース: 複数クレートの効率的な管理機能
  • セマンティックバージョニング: 自動的な互換性チェック
  • 豊富なエコシステム: Crates.ioの高品質なライブラリ群
  • クロスコンパイル: 複数プラットフォーム向けビルドサポート

デメリット

  • Rust専用: Rust以外の言語では使用不可
  • 学習コスト: 機能の豊富さによる初期学習の複雑さ
  • コンパイル時間: 大規模プロジェクトでの長いコンパイル時間
  • 依存関係サイズ: transitive dependenciesによるビルド成果物の肥大化
  • 互換性制約: Rust editionとCargoバージョンの依存関係
  • ネットワーク依存: crates.ioへのアクセス必要

参考ページ

書き方の例

基本的なプロジェクト管理

# 新規プロジェクト作成
cargo new my_project
cargo new my_library --lib

# 既存ディレクトリで初期化
cargo init
cargo init --lib

# 依存関係のビルド
cargo build
cargo build --release

# テスト実行
cargo test
cargo test --lib
cargo test integration_tests

# プロジェクト実行
cargo run
cargo run --bin my_binary
cargo run --example example_name

# チェック(型チェック・コンパイルエラー確認)
cargo check
cargo check --all-targets

Cargo.toml設定(Edition 2024)

[package]
name = "my_project"
version = "0.1.0"
edition = "2024"
authors = ["Your Name <[email protected]>"]
description = "A sample Rust project"
license = "MIT OR Apache-2.0"
repository = "https://github.com/username/my_project"
documentation = "https://docs.rs/my_project"
homepage = "https://my_project.example.com"
readme = "README.md"
keywords = ["cli", "example", "rust"]
categories = ["command-line-utilities"]
rust-version = "1.75"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
clap = { version = "4.0", features = ["derive"] }
anyhow = "1.0"
tracing = "0.1"
uuid = { version = "1.0", features = ["v4", "serde"] }

[dev-dependencies]
mockall = "0.12"
criterion = { version = "0.5", features = ["html_reports"] }
tempfile = "3.0"

[build-dependencies]
cc = "1.0"

[features]
default = ["cli"]
cli = ["clap"]
web = ["axum", "tower"]
experimental = []

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"

[profile.dev]
opt-level = 0
debug = true

ワークスペース設定

# ルートCargo.toml(ワークスペース定義)
[workspace]
members = [
    "core",
    "cli",
    "web-api",
    "shared-types"
]
default-members = ["cli"]
resolver = "2"

[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", default-features = false }
anyhow = "1.0"
uuid = { version = "1.0", features = ["v4"] }

[workspace.package]
version = "0.1.0"
edition = "2024"
authors = ["Your Name <[email protected]>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/username/my_workspace"

# ワークスペース全体の設定
[profile.release]
lto = true
codegen-units = 1
# メンバークレート: core/Cargo.toml
[package]
name = "my-core"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true

[dependencies]
serde.workspace = true
uuid.workspace = true
anyhow.workspace = true

[lib]
name = "my_core"
crate-type = ["lib"]

依存関係の高度な指定

[dependencies]
# バージョン指定の種類
time = "0.3.0"              # 0.3.0以上0.4.0未満
regex = "~1.5"              # 1.5.x系列
log = ">=0.4.0, <0.5.0"     # 範囲指定
chrono = "^0.4"             # キャレット(^0.4.0と同等)

# Git依存関係
my-git-dep = { git = "https://github.com/user/repo.git", branch = "main" }
another-dep = { git = "https://github.com/user/repo.git", tag = "v1.0" }
specific-commit = { git = "https://github.com/user/repo.git", rev = "abc123" }

# パス依存関係
local-lib = { path = "../local-lib" }
workspace-member = { path = "crates/shared" }

# 条件付き依存関係
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winuser", "shellapi"] }

[target.'cfg(unix)'.dependencies]
libc = "0.2"

# オプショナル依存関係
[dependencies]
serde_json = { version = "1.0", optional = true }

[features]
json = ["serde_json"]

ビルドとテスト

# 様々なビルドオプション
cargo build --all-targets          # 全ターゲットビルド
cargo build --workspace           # ワークスペース全体
cargo build --package my-core     # 特定パッケージ
cargo build --features json       # 特定フィーチャー有効
cargo build --no-default-features # デフォルトフィーチャー無効

# テスト実行
cargo test --workspace           # ワークスペース全体
cargo test --package my-core     # 特定パッケージ
cargo test --lib                # ライブラリテストのみ
cargo test --bins               # バイナリテストのみ
cargo test --examples           # サンプルテスト
cargo test unit_tests           # 特定のテスト

# ベンチマーク
cargo bench
cargo bench --package my-core

# ドキュメント生成
cargo doc --open              # ドキュメント生成・ブラウザで開く
cargo doc --no-deps           # 依存関係のドキュメント除外
cargo doc --workspace         # ワークスペース全体

パッケージ公開

# パッケージング
cargo package                  # .crateファイル作成
cargo package --list          # 含まれるファイル一覧
cargo package --allow-dirty    # 未コミット変更を許可

# 公開前チェック
cargo publish --dry-run       # 公開のドライラン

# 公開
cargo publish                 # crates.ioに公開
cargo publish --registry my-registry  # カスタムレジストリに公開

# クレート情報検索
cargo search serde           # crates.ioで検索
cargo search --limit 20 web  # 検索結果数制限

高度な機能と設定

# カスタムビルドスクリプト
[package]
build = "build.rs"

# ターゲット固有の設定
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"

[target.'cfg(target_os = "linux")']
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

# パッチ(依存関係の上書き)
[patch.crates-io]
my-crate = { git = "https://github.com/user/my-crate", branch = "fix" }
serde = { path = "../serde" }

# カスタムレジストリ
[registries]
my-registry = { index = "https://my-registry.com/git/index" }

# 設定
[source.crates-io]
replace-with = "my-mirror"

[source.my-mirror]
registry = "https://my-mirror.com/git/index"

ワークスペースでの開発フロー

# ワークスペース全体操作
cargo build --workspace
cargo test --workspace
cargo check --workspace

# 特定のクレート操作
cargo build -p my-core
cargo test -p my-cli
cargo run -p my-web-api

# 依存関係管理
cargo tree                    # 依存関係ツリー表示
cargo tree -p my-core         # 特定パッケージの依存関係
cargo tree --duplicates       # 重複依存関係の表示

# メタデータ取得
cargo metadata               # プロジェクト情報をJSON出力
cargo metadata --format-version 1

# クリーンアップ
cargo clean                  # ビルド成果物削除
cargo clean -p my-core       # 特定パッケージのみ

CI/CD とパフォーマンス最適化

# CI環境での高速化
export CARGO_HOME=/usr/local/cargo
export RUSTC_WRAPPER=sccache      # コンパイルキャッシュ

# キャッシュ最適化
cargo fetch                       # 依存関係事前取得
cargo build --frozen             # Cargo.lockを変更禁止
cargo build --offline            # オフラインビルド

# パフォーマンス分析
cargo build --timings            # コンパイル時間測定
cargo bloat                      # バイナリサイズ分析(要cargo-bloat)
cargo audit                      # セキュリティ監査(要cargo-audit)

# 並列テスト
cargo test -- --test-threads=4  # テスト並列数指定
cargo test -- --nocapture       # テスト出力表示