Skip to main content

Crate & Module

Crate

定義在Cargo.toml裡,指向Rust社群的套件庫,crago build時會先去crates.io抓對應的套件下來

note

crago build預設會安裝到$HOME/.cargo/bin

Cargo.toml
[dependency]
num = "0.4"
image = "0.13"

Use Package

這裡指的套件(Package),泛指可被引用的目標

  • In Project 在同一個專案內引用同為這個專案開發的其他套件
  • Vendors 使用第三方開發的套件,以語言生態系不同,大致又分為有託管無託管兩種目喲
FolderFile
RustCrateModule
GoWorkspace/Package檔名不重要,重要的是code第一行的package宣告
PythonPackageModule

In Project File

專案目錄會被稱為Crate Root,使用mod作為namespace並引用進其他file的內容

main.rs
  mod hello;

fn main() {
hello::say_hello();
}
hello.rs
pub fn say_hello() {
println!("Hello, world!");
}

In Project Folder

寫在同一個檔案,用mod關鍵字坎套

main.rs
mod foo {
fn say_foo() {
println!("This is Foo");
}
}

fn main() {
foo::say_foo();
}

Vendors Package

依賴Cargo.toml內的dependency,從crates.io上裝下來。使用直接import crate name就可以使用

也可以直接裝沒有在crates.io上的Git repo

cargo install --git github.com/mechsix/rustexample

main.rs
use image::io::Reader;

fn main() {
let img = Reader::open("example.png")?.decode()?;
// ...
}

Unit Test

Rust的test是使用tests mod,可以直接寫在code旁

#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;

#[test]
fn test_add() {
assert_eq!(add(1, 2), 3);
}
}

使用crate可以這樣直接執行。這預設會將所有的STDOUT隱藏起來

$ crate test

若想要執行test時保留STDOUT到console,可以這樣下

$ crate test -- --nocapture