【Rust】Rust ~ crate / module ~

◾️はじめに

https://dk521123.hatenablog.com/entry/2025/11/29/221911

では、「mod util;」を扱ったが、
今回は、crate / module について扱っていく。

目次

【0】用語整理
 1)crate
 2)module
【1】外部crateの導入
 1)cargo search
 2)導入
 3)use
 4)as
【2】関連する文法
 1)use
 2)as
【3】Hello world
 Step1:cargo new --lib でプロジェクト作成
 Step2:実装
 Step3:動作確認

【0】用語整理

1)crate

* 他のプログラムで言うと「ライブラリ」「パッケージ」と同義

cf. crate(クレート) = (輸送用の)木箱、ケース

https://doc.rust-jp.rs/book-ja/ch07-01-packages-and-crates.html

より抜粋
~~~
バイナリかライブラリのどちらか
~~~

以下の関連記事でやったAxumも、AxumというCrateである。

Rust ~ Axum / 入門編 ~
https://dk521123.hatenablog.com/entry/2023/09/02/224707

2)module

* crate よりも一段階小さい構成要素。
 => 共通処理をモジュールとしてまとめて、
  更に複数モジュールをまとめたものがcrateになる

【1】外部crateの導入

# cargo search <keyword>
cargo search askama
<出力結果>
askama = "0.14.0"                     # Type-safe, compiled Jinja-like templates for Rust
・・・略・・・
askama_axum = "0.5.0+deprecated"      # Integration crates like `askama_axum` were removed from askama 0.13.
... and 112 crates more (use --limit N to see more)
note: to learn more about a package, run `cargo info <name>`

2)導入

* Cargo.toml に追加するだけ

Cargo.toml

[dependencies]
askama = "0.14.0"

【2】関連する文法

1)use

* 使用したいモジュールを指定する
 => crateをRootとして、後は、パスを「::」区切りで指定する

例1
https://dk521123.hatenablog.com/entry/2025/12/04/000102

// より抜粋
use askama::Template;

例2

mod utils;
use crate::utils::util::demo_module;

fn main() {
    let greeting = demo_module::say_hello("world");
    println!("Result: {}", greeting);
}

2)as

* 使用したいモジュールを別名で使いたい場合に使用する

例1

use askama::Template as template;

例2

mod utils;
use crate::utils::util::demo_module as module;

fn main() {
    let greeting = module::say_hello("world");
    println!("Result: {}", greeting);
}

【3】Hello world

Step1:cargo new --lib でプロジェクト作成

# cargo new --lib <PROJECT_NAME>
cargo new --lib hello_lib

実行後のフォルダ構成

hello_lib
├── Cargo.toml
└── src
    └── lib.rs

Step2:実装

* lib.rsを実装する

lib.rs

// 以下の関数を追加
pub fn say_hello(name: &str) -> String {
    format!("Hello, {}!", name)
}

// 以下は元からある。。。
pub fn add(left: u64, right: u64) -> u64 {
    left + right
}

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

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }
}

Step3:動作確認

* main.rs を追加して、そこから呼び出してテストしてみる

フォルダ構成

hello_lib
├── Cargo.toml
└── src
    ├── main.rs << Add
    └── lib.rs

main.rs

use hello_lib::say_hello;

fn main() {
    println!("{}", say_hello("World"));
}

実行

cargo run
# 「Hello, World!」が表示

関連記事

Rust ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/04/22/234808
Rust ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2025/11/26/224648
Rust ~ cargoコマンド ~
https://dk521123.hatenablog.com/entry/2025/12/12/011304
Rust ~ 保有権 ~
https://dk521123.hatenablog.com/entry/2023/05/04/213726
Rust ~ mod ~
https://dk521123.hatenablog.com/entry/2025/11/29/221911
Rust template engine ~ Askama / 入門編 ~
https://dk521123.hatenablog.com/entry/2025/12/04/000102