RUST 学习的难点:
- 实践中如何运用。
- 遇到坑时(生命周期、借用错误、自引用等)如何迅速解决。
- 大量标准库方法记忆及运用。
Cargo
Rust 的包管理工具。
包管理工具的意义是任何用户拿到你的代码,都可以运行起来,而不会因为各种包版本依赖焦头烂额。
创建简单的示例项目
创建项目
cargo new hello_world
cd hello_world
项目结构
.
├── Cargo.lock
├── Cargo.toml
├── src
└── main.rs
运行项目
- 自动编译和运行
cargo run
Compiling world_hello v0.1.0 (/home/xuhcjp/Code/VisualStudioCodeProjects/world_hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.16s
Running `target/debug/world_hello`
Hello, world!
- 手动
cargo build
# Finished dev [unoptimized + debuginfo] target(s) in 0.00s
./target/debug/hello_world
# Hello, world!
debug
模式,代码的编译速度会非常快,但是运行速度会慢。
生成 --release
程序。
cargo run --release
cargo build --release
cargo check
快速的检查代码是否能够编译通过。可以节省大量的编译时间。
Cargo.toml 和 Cargo.lock
Cargo.toml
和 Cargo.lock
是 cargo
的核心文件。
Cargo.toml
是cargo
特有的 项目数据描述文件。它存储了项目所有的元配置信息。Cargo.lock
是cargo
工具根据同一项目的toml
文件生成的 项目依赖详细清单。
通常只需修改Cargo.toml
文件。
如果你的项目是一个可运行的程序时,可以上传Cargo.lock
到 git 仓库。如果是一个依赖库项目,那么请把它添加到.gitignore
中。
Cargo.toml 信息
[package]
name = "world_hello"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
name
字段定义了项目名称, version
字段定义当前版本,新项目默认是 0.1.0
,edition
字段定义使用的Rust 大版本。
定义 项目依赖
使用 cargo
工具的最大优势在于,能够对该项目的各种依赖项进行方便、统一和灵活的管理。
在 Cargo.toml
中,主要通过各种依赖段落来描述该项目的各种依赖项:
- 基于 Rust 官方仓库
crates.io
,通过版本说明来描述。 - 基于 项目源代码的 git 仓库地址,通过URL来描述。
- 基于本地项目的绝对路径或者相对路径,通过类 Unix 模式的路径来描述。
具体写法:
[dependencies]
rand = "0.3"
hammer = { version = "0.5.0"}
color = { git = "https://github.com/bjz/color-rs" }
geometry = { path = "crates/geometry"}
标准的 Package 目录结构
一个典型的 Package
目录结构如下:
.
├── Cargo.lock
├── Cargo.toml
├── src/
│ ├── lib.rs
│ ├── main.rs
│ └── bin/
│ ├── named-executable.rs
│ ├── another-executable.rs
│ └── multi-file-executable/
│ ├── main.rs
│ └── some_module.rs
├── benches/
│ ├── large-input.rs
│ └── multi-file-bench/
│ ├── main.rs
│ └── bench_module.rs
├── examples/
│ ├── simple.rs
│ └── multi-file-example/
│ ├── main.rs
│ └── ex_module.rs
└── tests/
├── some-integration-tests.rs
└── multi-file-test/
├── main.rs
└── test_module.rs
这也是 Cargo
推荐的目录结构,解释如下:
Cargo.toml
和Cargo.lock
保存在package
根目录下- 源代码放在
src
目录下 - 默认的
lib
包根是src/lib.rs
- 默认的二进制包根是
src/main.rs
- 其它二进制包根放在
src/bin/
目录下
- 其它二进制包根放在
- 基准测试 benchmark 放在
benches
目录下 - 示例代码放在
examples
目录下 - 集成测试代码放在
tests
目录下