这篇文章是实战性质的,也就是说原理部分较少,属于经验总结,rust对于模块的例子太少了。rust特性比较多(悲),本文的内容可能只是一部分,实现方式也不一定是这一种。
关于 rust 模块的相关内容,准确来说:怎么在源码中引用其他模块的内容。
引用模块要搞清楚的:
mod 关键字:
use 关键字也有两个作用
如果我们想要调用一个函数,我们需要知道它的路径。路径有两种形式:
见文档: https://rustwiki.org/zh-CN/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html
四、关于 create 的定义和 cargo 管理下的 crate我们都知道通过 cargo 创建出的工程中 src/main.rs 就是程序的入口,但是还有更多的使用方式。
下面就是一些问题了
▾ src/ # 包含源文件的目录
lib.rs # 库和包的主要入口点
main.rs # 包生成可执行文件的主要入口点
▾ bin/ # (可选)包含其他可执行文件的目录
*.rs
▾ */ # (可选)包含多文件可执行文件的目录
main.rs
▾ examples/ # (可选)示例
*.rs
▾ */ # (可选)包含多文件示例的目录
main.rs
▾ tests/ # (可选)集成测试
*.rs
▾ */ # (可选)包含多文件测试的目录
main.rs
▾ benches/ # (可选)基准
*.rs
▾ */ # (可选)包含多文件基准的目录
main.rs
五、例子例一:单文件,主函数和 toy 模块
src/main.rs
mod toy {
pub fn run() {
println!("run toy");
}
}
fn main() {
toy::run();
}
输出
run toy
例二:两个文件,主函数和另一个文件夹 toy 模块
src/toy_implements.rs
pub fn run() {
println!("run toy_impl !");
}
src/main.rs
mod toy1 { // 方法1: 使用 include!
include!("./toy_implements.rs");
}
#[path ="./toy_implements.rs"]
mod toy2; // 方法2: 使用 path 属性定位文件位置
fn main() {
toy1::run();
toy2::run();
}
输出
run toy_impl !
run toy_impl !
例三:在 main.rs 中使用 mod toy;
src/toy.rs
pub fn run() {
println!("run toy_impl !");
}
src/main.rs
mod toy;
fn main() {
toy::run();
}
输出
run toy_impl !
例四:在 src/foo.rs 中使用 mod toy;
src/foo/toy.rs
pub fn run() {
println!("run toy_impl !");
}
src/foo.rs
mod toy;
fn say_hi() {
toy::run();
}
输出
run toy_impl !
例五:use 指令
之前,我们使用了 toy::run() 来调用 run 函数。现在,我们使用 use 关键字来导入 toy 模块里的内容,这样就能在 main 函数中直接使用
src/foo.rs
mod toy {
pub fn run() { // 注意使用 pub 关键字
println!("run toy");
}
}
fn main() {
use toy::*; // 使用 use 导入 toy 模块里的内容
run(); // 直接调用
}
例六: 在as配合use指令
src/foo.rs
mod toy {
pub fn run() { // 注意使用 pub 关键字
println!("run toy");
}
}
fn main() {
use toy::run as toy_run; // 使用 use as 导入 toy 模块里的内容
toy_run();
}
例七: 使用pub use命令在mod.rs合并打包其他模块的东西
src/toy/runner.rs
pub fn dog_run() { println!("dog is run !"); }
src/toy/fly.rs
pub fn fly_bird() { println!("bird is fly !"); }
src/toy/bear.rs
pub fn bear_eat() { println!("bear is eat fish !"); }
pub fn bear_sleep() { println!("bear is go sleep !"); }
src/toy/mod.rs
mod runner; // 引入同级 runner.rs 文件
mod fly; // 引入同级 fly.rs 文件
mod bear; // 引入同级 bear.rs 文件
pub use runner::dog_run; // 声明(导出) dog_run 函数
pub use fly::fly_bird as now_fly_brid; // 声明(导出) fly_bird 函数,并重命名为 now_fly_brid
pub use bear::*; // 声明(导出) dog_run 函数
src/main.rs
mod toy;
fn main() {
toy::dog_run();
toy::now_fly_brid();
toy::bear_eat();
toy::bear_sleep();
}
输出
dog is run !
bird is fly !
bear is eat fish !
bear is go sleep !
例七: 使用pub mod导出内部包,使用 crate 引用顶部内容
src/toy/cube/mod.rs
pub fn get_size() {
println!("size is in main");
crate::top_size(); // 必不可少的 crate 关键字
}
src/toy/mod.rs
pub mod cube;
src/main.rs
mod toy;
fn top_size() {
println!("top size one !")
}
fn main() {
toy::cube::get_size();
}
输出
size is in main
top size one !
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved