现在你已经安装了 Rust 和 Cargo,我们来编写第一个项目吧!
创建一个新项目
运行以下命令:
arduino
cargo new hello-rust
这会创建一个新的 Rust 项目,包含一个简单的 "Hello, world!" 程序。它将新建一个目录 hello-rust
,目录结构如下:
css
hello-rust/
├── Cargo.toml
└── src
└── main.rs
其中:
Cargo.toml
是项目的清单文件,记录了项目的元信息以及依赖项。src/main.rs
是程序的入口文件。
打开 src/main.rs
,你会看到如下内容:
arduino
fn main() {
println!("Hello, world!");
}
这就是一个最基本的 Rust 程序。
构建并运行
进入项目目录:
bash
cd hello-rust
构建项目:
cargo build
你会看到输出信息说明项目已被编译,生成的可执行文件默认位于 target/debug/
目录下。
运行程序:
arduino
cargo run
你会看到输出:
Hello, world!
检查代码
你可以使用 Cargo 检查代码是否有语法错误或警告,而不进行编译:
sql
cargo check
这通常比完整构建更快。
查看项目依赖信息
运行以下命令可以查看项目的依赖树:
cargo tree
目前我们还没有添加任何依赖项,因此只会显示标准库部分。
刚刚完成了以下操作:
- 使用
cargo new
创建了一个新的 Rust 项目。 - 使用
cargo build
编译项目。 - 使用
cargo run
执行项目。 - 使用
cargo check
检查语法。 - 了解了
Cargo.toml
和项目结构。