zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    剑指Offer 19 正则表达式匹配
    剑指Offer 37 序列化二叉树
    剑指Offer 36 二叉搜索树与双向链表
    剑指Offer 35 复杂链表的复制
    剑指Offer 45 把数组排成最小的数
    华为有AI,这场转型战有点大
    NLP&深度学习:近期趋势概述
    2018年度10大新兴技术:人工智能、量子计算、增强现实等
    外媒评李开复的《AI·未来》:四大浪潮正在席卷全球
    商汤科技汤晓鸥:其实不存在AI行业,唯一存在的是“AI+“行业
  • 原文地址:https://www.cnblogs.com/pu369/p/15151824.html
Copyright © 2011-2022 走看看