Cargo のworkspace
セクションを使います。このセクションにmembers
というキーを追加し、その値にはパッケージ名を文字列にした配列を置きます。例えばそれは以下のようになります。
[workspace]
members = [
"plus-one",
"there-is-plus-one-as-dependency"
]
このファイルはルートとなるディレクトリでcargo init
を実行し生成されたCargo.toml
を編集するといいと思います。
plus-one
はモジュールで、there-is-plus-one-as-dependency
はそれを使うメイン処理を書く場所という想定です。この想定で例を見てみます。
plus-one モジュール
モジュールも Cargo でひな形が作れます。それはcargo init --lib <workspace-name>
で作れます。つまり今回の場合、cargo init --lib plus-one
になります。
実行後ディレクトリにplus-one/
と、その中にsrc/lib.rs
ファイルができてます。中身を書き換えます。
pub fn plus_one(num: i32) -> i32 {
num + 1
}
#[cfg(test)]
mod tests {
#[test]
fn plus_one_works() {
assert_eq!(34, crate::plus_one(33));
}
}
plus_one
関数を定義しました。これは数値を与えると+1
した値を返してくれる関数です。
一応テストも書いています。ワークスペースなプロジェクトではルートディレクトリでcargo test
するだけで各ワークスペースでテストを走らせてくれます。
cargo test
# ...
# running 1 test
# test tests::plus_one_works ... ok
# ...
次に上の関数を使うワークスペース作ります。プロジェクトルートディレクトリで、今度はcargo init
つまり--lib
無しで作ります。
cargo init there-is-plus-one-as-dependency
また同じようにthere-is-plus-one-as-dependency/
ができsrc/main.rs
が作られたのでこのファイルでplus_one
関数を使ってみます。
fn main() {
println!("{}", plus_one::plus_one(33));
}
上記の通り単にモジュール名から関数を辿って使うだけです。plus_one
から辿っているのは-
は_
に変換される為です。
メイン処理もプロジェクトルートディレクトリからcargo run
で使えます。34
と出てくれば完璧です。
➜ cargo run
Compiling there-is-plus-one-as-dependency v0.1.0 (/private/tmp/monorepo/there-is-plus-one-as-dependency)
Finished dev [unoptimized + debuginfo] target(s) in 0.56s
Running `target/debug/there-is-plus-one-as-dependency`
34