クレート: 配布するライブラリなどの配布単位となるもの。ライブラリ群はクレートとしてまとめられている。
モジュール: クレート内に用意されているライブラリ群
useを使い、クレートとその中にある利用したいモジュールをインポートすることで利用可能になる
$ cargo new –lib mymodule
use mymodule::add;
fn main() {
let x = 10;
let y = 20;
let res = add(x, y);
println!("answer: {} + {} = {}", x, y, res);
}
calcモジュールの中にadd関数を置く
pub mod calc {
pub fn add(left: usize, right: usize) -> usize {
left + right
}
}
モジュールのテストはcargo testで実行する
use super::*; は親モジュール内の全てのモジュールをインポートする
### テスト用のマクロ
assert_eq!()
assert_ne!()
assert!()
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;
}
}
テストコード
#[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);
}
}
}