下面,我们开发一个简单的示例项目来进一步学习。
4.1 创建项目
- 使用命令【cargo new hello-world】创建一个由cargo管理的项目
c:\work\rustApp>cargo new hello-world
Creating binary (application) `hello-world` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
c:\work\rustApp>
-
项目的目录结构为:
├── .git
├── .gitignore
├── Cargo.toml (项目配置信息)
└── src (编写源代码目录)
└── main.rs (cargo创建的Hello World 案例) -
main.rs 代码如下:
fn main() {
println!("Hello, world!");
}
示例中定义了入口函数:main,函数体内使用宏 println! 在命令行中打印 “Hello, world!”。
- 使用命令【cargo run】,将编译项目的源代码,生成可执行文件并运行。
c:\work\rustApp\hello-world>cargo run
Compiling hello-world v0.1.0 (C:\work\rustApp\hello-world)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.50s
Running `target\debug\hello-world.exe`
Hello, world!
c:\work\rustApp\hello-world>
程序运行时打印 “Hello, world!”。
- Cargo.toml 文件中内容如下:
[package]
name = "hello-world"
version = "0.1.0"
edition = "2024"
[dependencies]
package:包区域
name:项目名称
version:项目版本
edition:rust 版本
dependencies:依赖项区域,用于列出项目的依赖项。这些依赖项是Rust包,也称为“crates”,它们提供了项目所需的功能或库。Cargo(Rust的包管理器)能够自动下载、编译和链接这些依赖项,从而简化项目的构建过程。
每个依赖项通过其名称和版本号(或版本范围)来指定。版本号遵循语义化版本控制(Semantic Versioning,简称SemVer)的规范,通常格式为“主版本号.次版本号.修订号”,例如 1.2.3。有时,还可以指定预发布版本或元数据。
4.2 调试代码
- 在 main.ts 中增加一些调试代码来了解简单的调试方法,代码如下:
fn main() {
println!("Hello, world!");
// 1. 使用 println! 宏进行简单调试
let x = 42;
println!("Debug: x = {:?}", x);
// 2. 使用 dbg! 宏(推荐)
let numbers = vec![1, 2, 3];
dbg!(&numbers);
// 3. 条件断点示例
for i in 0..10 {
if i == 5 {
// 在这里设置断点
println!("到达断点位置");
}
}
}
4.3 常用的调试特性
- 使用 dbg! 宏:
// dbg! 宏会打印文件名、行号和表达式的值
let a = 1;
let b = dbg!(a * 2) + 1;
// 输出类似:[src/main.rs:2] a * 2 = 2
- 自定义 Debug 实现:
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
// 或手动实现 Debug
impl std::fmt::Debug for Point {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Point({}, {})", self