1 mod和文件系统

  • 执行cargo new时,不指定项目类型,则默认创建库项目

    1.1 定义模块```

    mod network{ fn connect(){} }

mod client{ fn connect(){} }

  1. <a name="804c1c1b"></a>
  2. ## 1.2 模块可嵌套

mod client { fn connect() { } }

mod network { fn connect() { }

  1. mod server {
  2. fn connect() {
  3. }
  4. }

}

  1. <a name="TLzOp"></a>
  2. ## 1.3 模块的文件系统规则
  3. - 对于模块foo,在lib.rs中用mod foo;声明模块
  4. - 若模块foo没有子模块,则在foo.rs中写模块代码
  5. - 若模块foo有子模块,则创建目录foo,在foo/mod.rs中写模块代码,声明子模块;
  6. - 总之,在lib.rs/mod.rs中声明顶级模块/非顶级模块;在 模块名(顶级模块)/mod(非顶级模块).rs文件中写模块代码,声明其子模块;目录层级代表模块层级。
  7. <a name="kGAid"></a>
  8. # 2 使用pub控制可见性
  9. - 项目(模块/函数)默认是私有的,使用pub修饰使之变成公有的,可从外部访问
  10. - 如果一个项是公有的,它能被任何父模块访问
  11. - 如果一个项是私有的,它只能被当前模块或其子模块访问
  12. <a name="nNio4"></a>
  13. # 3 使用use导入命名
  14. <a name="YDe7Q"></a>
  15. ## 3.1 使用函数全名调用,写法复杂

pub mod a { pub mod series { pub mod of { pub fn nested_modules() {} } } }

fn main() { a::series::of::nested_modules(); }

  1. <a name="M37Wf"></a>
  2. ## 3.2 使用use导入名称,写法简单

use a::series::of;

fn main() { of::nested_modules(); }

  1. <a name="ycCor"></a>
  2. ## 3.3 use可以导入函数

use a::series::of::nested_modules;

fn main() { nested_modules(); }

  1. <a name="VfkL8"></a>
  2. ## 3.4 use可以导入枚举值

enum TrafficLight { Red, Yellow, Green, }

use TrafficLight::{Red, Yellow};

fn main() { let red = Red; let yellow = Yellow; let green = TrafficLight::Green; // because we didn’t use TrafficLight::Green }

  1. - use *进行全局导入

use TrafficLight::*;

fn main() { let red = Red; let yellow = Yellow; let green = Green; }

  1. - 注意externuse的差别:extern crate导入外部库(crate),只用于外部库;use相当于符号别名,可避免写(内部或者模块)函数、变量的全名,而只用写短名称。
  2. <a name="8Fhse"></a>
  3. # 4 源代码

extern crate chap07;

pub mod a { pub mod series { pub mod of {

  1. #[derive(Debug)]
  2. pub enum TrafficLight {
  3. Red,
  4. Yellow,
  5. Green,
  6. }
  7. #[derive(Debug)]
  8. pub enum Boolean{
  9. True,
  10. False,
  11. }
  12. pub fn nested_modules() {
  13. println!("nested_modules");
  14. }
  15. }
  16. }

}

// 可以直接导入函数 use a::series::of::nested_modules; // 可以导入枚举类型和枚举值 use a::series::of::TrafficLight; use a::series::of::TrafficLight::{Yellow,Green}; // 可以用进行全局导入 use a::series::of::Boolean::;

use chap07::network::*;

fn main(){

  1. chap07::client::connect();
  2. connect();
  3. a::series::of::nested_modules();
  4. nested_modules();
  5. println!("red: {:?} yellow: {:?} green: {:?}",TrafficLight::Red,Yellow,Green);
  6. println!("true({:?}) or false({:?})",True,False);

} ```