rust模块化
模块化
关键字
模块以文件为单位
mod
最重要的关键字,引用以后即可用
use
引入的防范可以使用缩写
例子
同级文件
src/main.rs
pub mod dog;
fn main() {
dog::sleep();
crate::dog::dog1::bark();
crate::dog::dog2::bark();
}
src/dog.rs
pub fn sleep() {
println!("呼...呼...");
}
pub mod dog1 {
pub fn bark() {
println!("嗷...呜...");
}
}
pub mod dog2 {
pub fn bark() {
println!("汪!汪!");
}
}
多级模块
src/sub/mod.rs
pub mod demo1;
pub mod demo2;
pub use demo1::*;
// pub use demo2::sub;
src/sub/demo1.rs
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
src/sub/demo2.rs
pub fn sub(x: i32, y: i32) -> i32 {
x - y
}
src/main.rs
mod sub;
// use sub::add;
fn main() {
let result = sub::add(1, 2);
println!("1 + 2 = {}", result);
let result = sub::demo2::sub(1, 2);
println!("1 - 2 = {}", result);
}