Rust包和Crate超详细讲解

包和crate

  • 通过相关功能进行分组和划分不同的功能代码, 将代码分割成多个模块和多个文件组织代码, 一个包包含 多个crate 和一个可选的crate, Cargo 类似C++ 提供一个工作空间命名 类似JAVA中包空间。
  • 避免重复造轮子, 其他代码通过公关接口进行调用。
  • 模块系统: 包,Crates(模块树形结构,库和二进制项目), 模块, 路径。
  • *crate 是一个二进制项/ 库, rust编译以crate root源文件为起点,包中包含一个Cargo.toml 描述如何构建crate.

$ cargo new my-project

Created binary (application) `my-project` package

$ ls my-project

Cargo.toml

src

$ ls my-project/src

main.rs

Cargo 遵循一个约定 src/main.rs是一个与包同名二进制crate的根,如果包中同时包含src/main.rs, src/lib.rs 表示拥有多个与包同名的crate, 每个src/bin 文件都会被编译成独立的库

模块控制作用域与私有性

模块能够将库中代码进行分组, 提供可读性和重用性

use 引入外部依赖, pub公有关键字, as关键字 glob运算符。

// 一个包包含其他内置函数模块的 front_of_house
mod front_of_house {
    mod hosting {
        fn add_to_waitlist() {}
        fn seat_at_table() {}
    }
    mod serving {
        fn take_order() {}
        fn serve_order() {}
        fn take_payment() {}
    }
}
crate
 └── front_of_house
     ├── hosting
     │   ├── add_to_waitlist
     │   └── seat_at_table
     └── serving
         ├── take_order
         ├── serve_order
         └── take_payment

###模块中路径

  • rust如何在一个模块中找到一个项,路径有两种形式, 跟着一个:: 作为分割标识符
  • 绝对路径: 从crate根开始
  • 相对路径 : 以self, super
mod front_of_house {
    mod hosting {
        fn add_to_waitlist() {}
    }
}
pub fn eat_at_restaurant() {
    // 绝对路径
    crate::front_of_house::hosting::add_to_waitlist();
    // 相对路径
    front_of_house::hosting::add_to_waitlist();
}

如上此代码不能编译 原因在于 hosting 在 mod的内部, 属于私有的模块 不能被外部调用 ,rust中默认所有项(函数、方法、结构体、枚举、模块和常量)都是私有的。

父模块不能使用子模块的所有项,但是子模块可以,如果想要外部调用 必须的要增加 pub 关键字进行暴露

pub fn eat_at_restaurant() {
    // 绝对路径
    crate::front_of_house::hosting::add_to_waitlist();
    // 相对路径
    front_of_house::hosting::add_to_waitlist();
}

use 进行模块引入

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
        fn seat_at_table() {}
    }
    mod serving {
        fn take_order() {}
        fn serve_order() {}
        fn take_payment() {}
    }
}
use crate::front_of_house::hosting;
use self::front_of_house::hosting;
pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}

解决将两个同类型引入同一个作用域 导致rust编译错误问题 使用as 关键字解决此等问题

use std::fmt::Result;
use std::io::Result as IoResult;

pub use 能够让其他人导入他们自己的作用域

pub use crate::front_of_house::hosting

使用外部包的话需要Cargo.toml 下面增加

rand = "0.8.3"

原文地址:https://blog.csdn.net/qq_27217017/article/details/123307706