2.7. プロジェクト依存関係の設定
cargo プロジェクトの依存関係を指定するには、プロジェクトディレクトリーの Cargo.toml ファイルを編集します。このセクション [dependencies] には、プロジェクトの依存関係の一覧が含まれます。各依存関係は、次の形式で新しい行に一覧表示されます。
crate_name = version
Rust コードパッケージは crates と呼ばれます。
例2.6 プロジェクトへの依存関係の追加および cargo で構築
この例では、例2.2「cargo を使用したプロジェクトのビルド」 従って Rust プロジェクト helloworld を正常に構築していることを前提としています。
ディレクトリー helloworld に移動し、以下のソースコードが含まれるファイル src/main.rs を編集します。
extern crate time;
fn main() {
println!("Hello, world!");
println!("Time is: {}", time::now().rfc822());
}
このコードには、外部のクレート 時間 が必要になりました。以下のコードが含まれるように Cargo.toml ファイルを編集して、この依存関係をプロジェクト設定に追加します。
[package]
name = "helloworld"
version = "0.1.0"
authors = ["Your Name <yourname@example.com>"]
[dependencies]
time = "0.1"
cargo run コマンドを実行してプロジェクトをビルドし、作成された実行ファイルを実行します。
Red Hat Enterprise Linux 7 の場合:
$ scl enable rust-toolset-1.35 'cargo run' Updating registry `https://github.com/rust-lang/crates.io-index` Downloading time v0.1.38 Downloading libc v0.2.32 Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/helloworld` Hello, world! Time is: Fri, 13 Oct 2017 11:08:57Red Hat Enterprise Linux 8 の場合:
$ cargo run Updating registry `https://github.com/rust-lang/crates.io-index` Downloading time v0.1.38 Downloading libc v0.2.32 Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/helloworld` Hello, world! Time is: Fri, 13 Oct 2017 11:08:57
cargo は time crate とその依存関係 (crate libc) をダウンロードし、ローカルに保管し、依存関係を含むすべてのプロジェクトのソースコードをビルドし、最終的に生成される実行ファイルを実行します。
関連資料
- 依存関係の指定: 公式の cargo ドキュメント。