Rust(8) - 使用模組

Rust module 中需要用 pub 關鍵字決定要公開的 function, struct 和 field。

1. 從檔案 import 模組:

第一種比較簡單,如果在 main.rs 或 lib.rs 同資料夾中有模組檔案可以直接被引用。

src
├── main.rs
└── my_math.rs

在 my_math.rs 中加入 sub_two,並把 sub_two 設為 pub (public)。

設為 public 代表 my_math 公開的 sub_two 給別人使用。

pub fn sub_two(a:i32, b:i32) -> i32 {
    a - b
}

宣告 my_math 這個 module,使用 my_math::add_two 可以呼叫到函數。

mod my_math;

fn main() {
    let a: i32 = 10;
    let b: i32 = 10;
    let add_res = my_math::add_two(a, b);
    println!("add_res: {}", add_res);
}

2. 從資料夾 import:

當 my_math.rs 包含很多函數時,my_math.rs 會變得很龐雜。

這時候我們會把函數拆成小功能,每個小功能放在資料夾中。

src
├── main.rs
├── my_math
│   └── my_sub.rs // 拆分小功能
└── my_math.rs    // 直接 import my_math 中的功能

mod my_math 會建立 my_math 模組並對應 my_math.rs,而 my_math.rs 可以再對應到子模組。

mod my_math;

fn main() {
    let a: i32 = 10;
    let b: i32 = 10;
    let add_res = my_math::my_sub::sub_two(a, b);
    println!("add_res: {}", add_res);
}

my_math.rs 再引用 my_math/my_sub.rs。P

pub mod my_sub;

pub fn add_two(a:i32, b:i32) -> i32 {
    a+b
}

留言

熱門文章