跳转至

项目入门

1.1 编译运行 Rust 程序

Bash
1
2
3
4
5
6
7
8
9
cargo new <name>        # 创建一个新项目

cargo run               # 编译并运行程序( Debug 模式,编译快速但运行缓慢,因为编译器不会做优化)
cargo build             # 编译程序( Debug 模式)
./target/debug/<name>   # 运行程序

cargo run --release     # 编译并运行程序( Release 模式,获得高性能的代码)
cargo build --release   # 编译程序( Release 模式)
./target/release/<name> # 运行程序

1.2 Cargo.toml 和 Cargo.lock

  • Cargo.toml 是 cargo 特有的项目数据描述文件。它存储了项目的所有元配置信息。
  • Cargo.lock 文件是 cargo 工具根据同一项目的 toml 文件生成的项目依赖详细清单,我们无需修改。

package 配置段落

TOML
1
2
3
4
[package]
name = "world_hello"
version = "0.1.0"
edition = "2024"

name 字段定义了项目名称,version 字段定义当前版本,新项目默认是 0.1.0,edition 字段定义了我们使用的 Rust 大版本。

定义项目依赖

TOML
1
2
3
4
5
[dependencies]
rand = "0.3"
hammer = { version = "0.5.0"}
color = { git = "https://github.com/bjz/color-rs" }
geometry = { path = "crates/geometry" }
  • 基于 Rust 官方仓库 crates.io,通过版本说明来描述
  • 基于项目源代码的 git 仓库地址,通过 URL 来描述
  • 基于本地项目的绝对路径或者相对路径,通过类 Unix 模式的路径来描述