Rust でライブラリを作成し、メインのプログラムからそのライブラリを利用する方法を説明します。モジュールの理解を深めるためのシンプルなサンプルを紹介します。
プロジェクトの作成
まず、メインのプロジェクトとライブラリを作成します。
cargo new main_app
cargo new --lib utils
これで以下のようなディレクトリ構成になります。
.
├── utils
│ ├── Cargo.toml
│ └── src
│ ├── lib.rs
│ └── math
│ ├── mod.rs
│ └── operations.rs
└── main_app
├── Cargo.toml
└── src
└── main.rs
ライブラリの実装
ライブラリ (utils
) にネストしたモジュールを定義します。
utils/src/lib.rs
:
pub mod math;
utils/src/math/mod.rs
:
pub mod operations;
utils/src/math/operations.rs
:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
このライブラリには math
というモジュールを作成し、その中に operations
というサブモジュールを作成しました。
メインプロジェクトでライブラリを利用
メインプロジェクト (main_app
) で utils
を利用するために、依存関係を追加します。
main_app/Cargo.toml
に以下を追加:
[dependencies]
utils = { path = "../utils" }
次に、メインプログラム (main_app/src/main.rs
) で utils
を使います。
main_app/src/main.rs
:
use utils::math::operations;
fn main() {
let sum = operations::add(5, 3);
let difference = operations::subtract(10, 4);
println!("5 + 3 = {}", sum);
println!("10 - 4 = {}", difference);
}
実行
以下のコマンドで実行できます。
cd main_app
cargo run
出力:
5 + 3 = 8
10 - 4 = 6
まとめ
cargo new --lib
でライブラリを作成pub mod
でネストしたモジュールを定義Cargo.toml
にパスを指定して依存関係を追加use
を利用してメインプログラムでライブラリを呼び出し
Rust のモジュールとライブラリの基本が理解しやすいサンプルになっています。