1. 安装 Rust
Linux/macOS 系统:
1
| curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
Windows 系统:
验证安装:
1 2
| rustc --version cargo --version
|
2. Hello World 程序
创建项目目录:
1 2
| mkdir hello_rust cd hello_rust
|
创建源文件 main.rs:
1 2 3 4 5 6 7 8 9 10 11 12 13
| fn main() { println!("Hello, World!"); let name = "Rust"; println!("Hello, {}!", name); let x = 42; println!("The answer is: {}", x); }
|
3. 编译和运行
方法一:直接编译(rustc)
1 2 3 4 5 6 7 8
| rustc main.rs
./main
main.exe
|
方法二:使用 Cargo(推荐)
1 2 3 4 5 6 7 8 9 10 11 12
| cargo new hello_rust cd hello_rust
cargo run
cargo build
cargo test
|
4. Cargo 项目示例
创建 Cargo.toml(Cargo 自动生成):
1 2 3 4 5 6
| [package] name = "hello_rust" version = "0.1.0" edition = "2021"
[dependencies]
|
src/main.rs 内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| fn main() { println!("Hello, World!"); let language = "Rust"; let year = 2024; println!("Learning {} in {}", language, year); let a = 10; let b = 20; let sum = a + b; println!("{} + {} = {}", a, b, sum); }
|
5. 运行结果示例
1 2 3 4 5 6 7
| $ cargo run Compiling hello_rust v0.1.0 Finished dev [unoptimized + debuginfo] target(s) Running `target/debug/hello_rust` Hello, World! Learning Rust in 2024 10 + 20 = 30
|
常用 Cargo 命令
1 2 3 4 5 6
| cargo new <项目名> cargo build cargo run cargo check cargo test cargo doc --open
|
小贴士
- Rust 文件命名:使用
.rs 扩展名
- 缩进:推荐使用 4 个空格
- 分号:每个语句结尾需要分号
println! 后面的 !:表示这是宏而不是普通函数
现在你已经成功安装了 Rust 并运行了第一个程序!🎉