在写Rust项目时,源文件多了,就涉及到如何管理源文件。需要对不同功能的文件进行合并处理,不再是所有源文件平铺的结构。下面是本次实例的源文件文档结构:
├── Cargo.lock
├── Cargo.toml
├── mylib
│ ├── Cargo.lock
│ ├── Cargo.toml
│ ├── src
│ │ ├── lib.rs
│ │ └── tree.rs
│ └── tests
│ ├── common
│ │ ├── alwaystrue.rs
│ │ └── mod.rs
│ ├── intergration_test.rs
│ └── othre_test.rs
└── src
├── animal
│ ├── fish.rs
│ └── mod.rs
├── dog.rs
└── main.rs
main.rs 是程序入口;dog.rs 和 animal下的文件是程序模块文件;mylib是本地库文件;mylib/tests是库的测试文件,不需要管。
Cargo.toml
[package]
name = "mod-demo"
version = "0.1.0"
authors = [""]
[dependencies]
mylib = { path = "./mylib" }
rust-crypto = "0.2"
在[dependencies]中注意要引入本地库和网络库。
main.rs
extern crate crypto;
extern crate mylib;
use crypto::digest::Digest;
use crypto::sha3::Sha3;
mod animal;
mod dog;
pub mod house {
pub mod inner_house {
pub fn print() {}
}
}
fn main() {
// 同一文件的mod
house::inner_house::print();
// 同级目录的mod
dog::say::nothing();
// 同级目录的mod文件集合
animal::cat::say::nothing();
animal::fish::say::nothing();
// 本地私有库的mod
mylib::tree::assert::have_name();
// 外部引入库的mod
let mut hasher = Sha3::sha3_256();
hasher.input_str("hello world");
}
dog.rs
pub mod say {
pub fn nothing() {}
}
animal/mod.rs
pub mod fish;
pub mod cat {
pub mod say {
pub fn nothing() {}
}
}
animal/fish.rs
mod goldfish {
pub mod say {
pub fn nothing() {}
}
}
pub mod say {
pub fn nothing() {
super::goldfish::say::nothing(); // 相对路劲
crate::animal::fish::goldfish::say::nothing(); // 绝对路劲
}
}
mylib/lib.rs
pub mod tree;
#[cfg(test)]
mod tests {
use tree::*;
#[test]
fn test_tree() {
assert_eq!(true, assert::have_name());
assert_eq!(true, super::tree::assert::have_name());
}
}
mylib/tree.rs
pub mod assert {
pub fn have_name() -> bool {
return true;
}
}
相信通过上面一个简单的例子,对于Rust项目文件该如何管理应该有一个清晰的理解。