Rust 入门 - Mod
2021-05-30 本文已影响0人
Lee_dev
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {
println!("add_to_waitlist")
}
fn seat_at_table() {}
}
mod serving {
fn take_order() {}
fn server_order() {}
fn take_payment() {}
}
}
绝对路径(absolute path)从 crate 根开始,以 crate 名或者字面值 crate 开头。
相对路径(relative path)从当前模块开始,以 self、super 或当前模块的标识符开头。
pub fn eat_at_restaurant() {
crate::front_of_house::hosting::add_to_waitlist();
front_of_house::hosting::add_to_waitlist();
}
使用 super 开头来构建从父模块开始的相对路
fn serve_order() {}
mod back_of_house {
fn fix_incorrect_order() {
cook_order();
super::serve_order();
}
fn cook_order() {}
}
创建公有的结构体和枚举
mod back_of_house1 {
// 带有公有和私有字段的结构体 , 结构体可以单个共有
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
pub fn summer(toast: &str) -> Breakfast {
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peaches"),
}
}
}
}
pub fn eat_at_restaurant1() {
let mut meal = back_of_house1::Breakfast::summer("Tom");
meal.toast = String::from("Wheat");
println!("I'd like {} toast please", meal.toast);
}
如果将枚举设为公有,则它的所有成员都将变为公有
mod back_of_house2 {
pub enum Appetizer {
Soup,
Salad,
}
}
pub fn eat_at_restaurant3() {
let o1 = back_of_house2::Appetizer::Salad;
let o2 = back_of_house2::Appetizer::Soup;
}
使用 use 关键字将名称引入作用域(简化路径使用)
mod front_of_house4 {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house4::hosting;
pub fn eat_at_restaurant4() {
hosting::add_to_waitlist()
}
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert(1, 2);
println!("map = {:?}", map);
}
最好只引入到父模块,防止冲突
use std::fmt;
use std::io;
fn function1() -> fmt::Result {
--snip--
}
fn function2() -> io::Result<()> {
--snip--
}
使用 as 关键字提供新的名称
use std::fmt::Result;
use std::io::Result as IoResult;
fn fn1() -> Result {}
fn fn2() -> IoResult<()> {}
当使用 use 关键字将名称导入作用域时,在新作用域中可用的名称是私有的。如果为了让调用你编写的代码的代码能够像在自己的作用域内引用这些类型,可以结合 pub 和 use。这个技术被称为 “重导出(re-exporting)”,因为这样做将项引入作用域并同时使其可供其他代码引入自己的作用域。
mod front_of_house5 {
pub mod hosting5 {
pub fn add_to_waitlist() {}
}
}
pub use crate::front_of_house5::hosting5;
pub fn eat_at_restaurant5() {
hosting::add_to_waitlist();
hosting::add_to_waitlist();
hosting::add_to_waitlist();
}
使用外部包
[dependencies]
rand = "0.5.5"
use rand::Rng;
fn main() {
let secret_number = rand::thread_rng().gen_range(1, 101);
}
嵌套路径来消除大量的 use 行
use std::cmp::Ordering;
use std::io;
use std::{cmp::Ordering, io};
通过 glob 运算符将所有的公有定义引入作用域
use std::collections::*;