Rustモジュールの作成

クレート: 配布するライブラリなどの配布単位となるもの。ライブラリ群はクレートとしてまとめられている。
モジュール: クレート内に用意されているライブラリ群
useを使い、クレートとその中にある利用したいモジュールをインポートすることで利用可能になる

$ cargo new –lib mymodule

1
2
3
4
5
6
7
8
use mymodule::add;
 
fn main() {
    let x = 10;
    let y = 20;
    let res = add(x, y);
    println!("answer: {} + {} = {}", x, y, res);
}

calcモジュールの中にadd関数を置く

1
2
3
4
5
pub mod calc {
    pub fn add(left: usize, right: usize) -> usize {
        left + right
    }
}

モジュールのテストはcargo testで実行する
use super::*; は親モジュール内の全てのモジュールをインポートする

### テスト用のマクロ
assert_eq!()
assert_ne!()
assert!()

1
2
3
4
5
6
7
8
9
10
11
12
pub mod calc {
 
    pub fn is_prime(num: unsize) -> bool {
        let mut f = true;
        for n in 2..(num/ 2) {
            if num % n == 0 {
                f = false;
            }
        }
        return f;
    }
}

テストコード

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#[cfg(test)]
mod tests {
    use super::*;
 
    #[test]
    fn it_is_prime() {
        let data = [
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29
        ];
 
        for n in data {
            let res = calc::is_prime(n);
            assert_eq!(res, true);
        }
    }
    #[test]
    fn it_isnot_prime() {
        let data = [
            4, 6, 9, 10, 12, 14, 15, 16, 18, 20
        ];
 
        for n in data {
            let res = calc::is_prime(n);
            assert_eq!(res, true);
        }
    }
}