Getting Started
快速开始
What you’ll learn: How to install Rust, create the first project, and map the Cargo workflow to what Java developers know from Maven or Gradle.
本章将学习: 如何安装 Rust、创建第一个项目,以及怎样把 Cargo 工作流和 Java 开发者熟悉的 Maven、Gradle 对上号。Difficulty: 🟢 Beginner
难度: 🟢 初级
Install the Toolchain
安装工具链
Use rustup to install Rust and manage toolchains:
使用 rustup 安装 Rust 并管理工具链:
winget install Rustlang.Rustup
rustup default stable
rustc --version
cargo --version
The Java analogy is a mix of JDK installer plus SDK manager, except Rust keeps the toolchain story much tighter.
如果拿 Java 类比,这有点像把 JDK 安装器和 SDK 管理器揉到了一起,只是 Rust 的工具链故事要紧凑得多。
Create the First Project
创建第一个项目
cargo new hello-rust
cd hello-rust
cargo run
That single command sequence creates the project, compiles it, and runs it.
这一串命令会把项目创建、编译和运行一次性做完。
Cargo vs Maven / Gradle
Cargo 与 Maven / Gradle 对照
| Activity 活动 | Java habit Java 习惯 | Rust habit Rust 习惯 |
|---|---|---|
| initialize project 初始化项目 | gradle init or archetype | cargo new |
| compile 编译 | mvn package or gradle build | cargo build |
| run tests 运行测试 | mvn test or gradle test | cargo test |
| run app 运行程序 | plugin task | cargo run |
| add dependency 添加依赖 | edit build file | cargo add crate_name |
First Program
第一个程序
fn main() {
println!("Hello, Rust!");
}
There is no class wrapper, no public static void main, and no object ceremony around the entry point.
这里没有类壳子、没有 public static void main,也没有围绕入口点的对象仪式感。
Reading Arguments
读取参数
fn main() {
let args: Vec<String> = std::env::args().collect();
println!("{args:?}");
}
For anything beyond trivial parsing, use clap.
只要参数解析稍微复杂一点,就上 clap。
The Three Commands to Memorize
先记住这三个命令
cargo check
cargo test
cargo run
cargo check is especially valuable for new Rust developers because it gives fast feedback without producing a final binary.
对刚学 Rust 的人来说,cargo check 特别值钱,因为它不用真的产出最终二进制,就能给出很快的反馈。
Advice
建议
- Install
rust-analyzerin the editor immediately.
编辑器里第一时间装上rust-analyzer。 - Prefer
cargo checkduring rapid iteration.
快速迭代阶段优先跑cargo check。 - Keep the first project small; ownership is easier to learn on tiny programs.
第一个项目尽量做小,所有权在小程序里更容易学明白。
Once Cargo and the compiler stop feeling foreign, the rest of Rust becomes much easier to approach.
只要 Cargo 和编译器不再显得陌生,后面的 Rust 学习难度就会明显往下掉。