《Rust Programming Language》- 05 - Packages, Crates And Modules
Crate
A crate is the smallest amount of code that the Rust compiler considers at a time.
Two types of crates:
- Binary Crates
- Binary crates are programs you can compile to an executable that you can run, such as a command-line program or a server.
- Contains a
main
function
- Library Crates 4. Do not compile to an executable. 5. Do not have a
main
function.
Package
A package is a bundle of one or more crates that provides a set of functionality.
A package contains a Cargo.toml file that describes how to build those crates.
Modules
Modules let us organize code within a crate for readability and easy reuse. Modules also allow us to control the access of items.
Paths
Both absolute and relative paths are followed by one or more identifiers separated by double colons (::
).
- An
absolute path
is the full path starting from a crate root; for code from an external crate, the absolute path begins with the crate name, and for code from the current crate, it starts with the literalcrate
. - A
relative path
starts from the current module and usesself
,super
, or an identifier in the current module.
Access Control
In Rust, all items (functions, methods, structs, enums, modules, and constants) are private to parent modules by default. If you want to make an item like a function or struct private, you put it in a module.
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {
println!("add_to_waitlist")
}
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
Import code with use
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {
println!("add_to_waitlist")
}
}
}
mod customer {
/* Use must happened within the scope */
use crate::front_of_house::hosting::add_to_waitlist;
pub fn eat_at_restaurant() {
add_to_waitlist();
}
}
use std::fmt::Result;
use std::io::Result as IoResult; // `as` to provide an alias
fn function1() -> Result {
// --snip--
Ok(())
}
fn function2() -> IoResult<()> {
// --snip--
Ok(())
}
External Packages
Add new dep in:Filename: Cargo.toml
rand = "0.8.5"
And then use them in your code:
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
//...
}
Import with nested paths & Glob Operator
use std::cmp::Ordering;
use std::io;
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
use std::{cmp::Ordering, io};
use std::io;
use std::io::Write;
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
use std::io::{self, Write};
Or if you want to import all with glob operator *
:
use std::collections::*;
Modules Cheat Sheet
- Start from the crate root: When compiling a crate, the compiler first looks in the crate root file (usually
src/lib.rs
for a library crate orsrc/main.rs
for a binary crate) for code to compile. - Declaring modules: In the crate root file, you can declare new modules; say, you declare a “garden” module with
mod garden;
. The compiler will look for the module’s code in these places:- Inline, within curly brackets that replace the semicolon following
mod garden
- In the file
src/garden.rs
- In the file
src/garden/mod.rs
- Inline, within curly brackets that replace the semicolon following
- Declaring submodules: In any file other than the crate root, you can declare submodules. For example, you might declare
mod vegetables;
insrc/garden.rs
. The compiler will look for the submodule’s code within the directory named for the parent module in these places:- Inline, directly following
mod vegetables
, within curly brackets instead of the semicolon - In the file
src/garden/vegetables.rs
- In the file
src/garden/vegetables/mod.rs
- Inline, directly following
- Paths to code in modules: Once a module is part of your crate, you can refer to code in that module from anywhere else in that same crate, as long as the privacy rules allow, using the path to the code. For example, an
Asparagus
type in the garden vegetables module would be found atcrate::garden::vegetables::Asparagus
. - Private vs public: Code within a module is private from its parent modules by default. To make a module public, declare it with
pub mod
instead ofmod
. To make items within a public module public as well, usepub
before their declarations. - The
use
keyword: Within a scope, theuse
keyword creates shortcuts to items to reduce repetition of long paths. In any scope that can refer tocrate::garden::vegetables::Asparagus
, you can create a shortcut withuse crate::garden::vegetables::Asparagus;
and from then on you only need to writeAsparagus
to make use of that type in the scope.
Example
backyard
├── Cargo.lock
├── Cargo.toml
└── src
├── garden
│ └── vegetables.rs
├── garden.rs
└── main.rs
Filename: src/main.rs
// Automatically find the crate 'src/garden/Asparagus'
use crate::garden::vegetables::Asparagus;
// Include the code from 'src/garden.rs'
pub mod garden;
fn main() {
let plant = Asparagus {};
println!("I'm growing {:?}!", plant);
}
Filename: src/garden.rs
pub mod vegetables;
相关文章
- 让我们用 Rust 重写那些伟大的软件吧
- 为什么我们应当将 Rust 用于嵌入式开发?
- Rust 1.56.0 版本和 Rust 2021 版次发布,新特性一览,及项目的迁移、升级
- RAII技术:在Rust中实现带有守卫的自旋锁,支持一定程度上的编译期并发安全检查
- 【Rust日报】2022-12-16 Cranelift的2022进展报告
- 【Rust日报】2023-01-03 Rust vs C++ 常见 Bug 对比
- 【Rust日报】2023-01-18 希望你能早点学到的 Rust 技巧
- Rust学习笔记Day11 类型系统及多态是如何实现的?
- Rust特征(Trait)
- RUST语言中常用的数据结构和设计模式的示例
- Rust最受喜爱却少有人用,Python仅排第六,2021全球开发者调查报告出炉
- Webpack 创始人推出比 Webpack“快 700 倍”的 Turbopack,基于 Rust 编写
- 从java到JavaScript(1),看Dart:对比Java/Go/Swift/Rust
- #新闻拍一拍# Oracle 调研如何避免让 Java 开发者投奔 Rust 和 Kotlin
- 深入浅出:MySQL中AND和OR运算符使用方法(mysql中and和or)
- 条件MySQL 子句之间`AND`操作符多条件查询(mysql多个and)
- MySQL中AND的使用方法解析(mysql中and的用法)
- MySQL中AND的使用方法及含义解析(mysql中and的含义)
- Mysql中强大的AND运算符的使用方法探究(mysql中and的使用)
- MySQL中的AND和OR使用逻辑运算符优化查询语句(mysql中and与or)
- Rust实现高性能Redis服务器集群(rust 实现redis)