标签:前缀 super imp 访问 ble 兼容 lan pre 声明
模块化有助于代码的管理和层次逻辑的清晰
Rust模块化有多种方式:
嵌套模块就是直接在要使用模块的文件中声明模块
mod food{//声明模块
pub struct Cake;
pub struct Smoothoe;
pub struct Pizza;
}
use food::Cake;//使用模块中的内容
fn main() {
let eateable=Cake;
}
一个.rs文件就是一个和文件同名的模块,在使用的地方要声明模块
file_module/
├── Cargo.toml
└── src
├── food.rs
└── main.rs
food.rs:
pub struct Cake;
pub struct Smoothoe;
pub struct Pizza;
main.rs
mod food;//声明模块
use food::Cake;//使用模块内容
fn main() {
let eatable=Cake;
}
dir_module_2015
├── Cargo.toml
└── src
├── food
│ ├── cake.rs
│ ├── mod.rs
│ ├── pizza.rs
│ └── smoothoe.rs
└── main.rs
cake.rs:
pub struct Cake;
pizza.rs
pub struct Pizza;
smoothoe.rs
pub struct Smoothoe;
mod.rs
pub mod cake;
pub mod pizza;
pub mod smoothoe;
use self::cake::Cake;
impl Cake {
pub fn judge(){
println!("cake is sweet");
}
}
main.rs
mod food;
use food::cake::Cake;
fn main() {
Cake::judge();
}
dir_module_2018
├── Cargo.toml
└── src
├── food
│ ├── cake.rs
│ ├── pizza.rs
│ └── smoothoe.rs
├── food.rs
└── main.rs
cake.rs:
pub struct Cake;
pizza.rs
pub struct Pizza;
smoothoe.rs
pub struct Smoothoe;
food.rs
pub mod cake;
pub mod pizza;
pub mod smoothoe;
use self::cake::Cake;
impl Cake {
pub fn judge(){
println!("cake is sweet");
}
}
main.rs
mod food;
use food::cake::Cake;
fn main() {
Cake::judge();
}
目前Rust兼容mod.rs写法和文件夹同目录下同名文件写法
create:绝对导入前缀,指向当前目的root模块(main.rs或lib.rs)。
self:指向于当前模块的元素,用于任何想要引入自身模块所包含的内容时。(例如父模块重新导出子模块 pub use self::cake::Cake;
)
super:指向父模块,用于从父模块导入元素。(如果模块bar希望访问副模块foo中的元素Foo,那么可以用super::foo::Foo)
标签:前缀 super imp 访问 ble 兼容 lan pre 声明
原文地址:https://www.cnblogs.com/yanshaoshuai/p/14407130.html