• Rust 学习之 Package、Crate、Module


    Shesh's blog的那篇Clear explanation of Rust’s module system写的太好了。

    详见http://www.sheshbabu.com/posts/rust-module-system/

    为加深理解,实际操作一下,直接做成最终版本项目结构:

    1     执行   cargo new my_project   然后在生成的src目录中新建目录routes和models

    2    在src目录下已有main.rs  ,再新建文件 config.rs    

          在routes目录下新建文件mod.rs  health_route.rs 和 user_route.rs

         在models目录下新建文件mod.rs 和 user_model.rs

    上述7个文件源码如下: 

    // main.rs
    mod config;
    mod routes;
    mod models;
    
    fn main() {
      routes::health_route::print_health_route();
      routes::user_route::print_user_route();
      config::print_config();
      println!("main");
    }
    // config.rs
         pub fn print_config() {
          println!("config");
        }

    routes目录下的

    // routes/mod.rs
    pub mod health_route;
    pub mod user_route;
    // routes/health_route.rs
         pub fn print_health_route() {
          println!("health_route");
        }
    // routes/user_route.rs
    pub fn print_user_route() {
          crate::models::user_model::print_user_model();
          println!("user_route");
        }

    models目录下的

    // models/mod.rs
      pub mod user_model;
    // models/user_model.rs
          pub fn print_user_model() {
          println!("user_model");
        }

    cargo run   ,可正常运行

    我对原文的理解:

    1 我们看到的是文件目录树(File System Tree),而编译器看到的是模块系统树(Module System Tree),两者并不对应。

    例如:main.rs中有mod config,编译器就会在同级目录中找config.rs文件或config目录

    2 子模块是由父级声明的,不是用自身文件名或目录名声明的。

    例如:main.rs中用mod routes声明,编译器就会在同级目录中找routes.rs文件或routes目录

    3 子模块函数要加 pub 关键字,才能被调用。子模块目录中的mod.rs中也要加pub关键字

    例如:main.rs中用mod routes声明后,routes目录下的mod.rs中又用pub mod user_route 声明 ;在user_route.rs中又用pub关键字暴露print_user_route函数,

    然后才能在main.rs中调用routes::user_route::print_user_route();

    4  config  routes  models 三个子模块都是项目Crate的直接子模块,例如:可在main.rs中用绝对路径进行调用的代码:

    crate::models::user_model::print_user_model();

     还可用super use 关键字,不详述。

    5 在Cargo.toml中添加外部依赖后,外部模块就全局可用了,不需要用mod关键字声明了。

    6 最外层是Package,其中有一个Cargo.toml  

    默认的项目的 `binary crate` 的入口文件是 src/main.rs
    默认的库 `library crate` 的入口文件是 src/lib.rs 库名称与Package的名称相同。

      Module 在一个crate内,将代码进行分组。

       

    参考:https://www.cnblogs.com/ishenghuo/p/13539547.html

    https://www.jianshu.com/p/b58489afc616

    https://blog.csdn.net/quicmous/article/details/113829830

  • 相关阅读:
    通过使用精简客户端,且不需要安装的客户端,配合PLSQL连接oracle数据库
    JDBC连接
    多线程TCP的socket通信
    基于UDP协议的socket通信
    基于TCP协议的socket通信
    设计模式之单例模式
    设计模式之代理模式
    设计模式之策略模式
    >hibernate-session中的方法
    >hibernate的四种状态
  • 原文地址:https://www.cnblogs.com/pu369/p/15151824.html
Copyright © 2020-2023  润新知