🦀 第01课:Rust概述与安装

欢迎来到Rust语言入门课程!Rust是一门赋予每个人构建可靠且高效软件能力的语言。本课将带你了解Rust的设计理念、核心优势,并完成开发环境的搭建。

入门基础 第1/25课

学习目标:理解Rust语言的核心设计理念,完成Rust开发环境安装,编写并运行第一个Rust程序

🔍 Rust是什么?

Rust是由Mozilla研究院于2010年首次发布的系统编程语言,由Graydon Hoare设计。它专注于三个目标:安全并发高性能。Rust连续多年在Stack Overflow开发者调查中被评为"最受喜爱的编程语言"。

Rust的核心设计理念

1. 内存安全 —— 无需垃圾回收

Rust通过所有权系统(Ownership System)在编译期保证内存安全,不需要垃圾回收器(GC),也不需要手动管理内存。这是Rust最革命性的创新。

2. 零成本抽象

Rust的高级特性(如泛型、trait、迭代器)在编译后与手写底层代码性能相当。你不需要在抽象和性能之间做选择。

3. 无数据竞争的并发

Rust的类型系统和所有权模型在编译期就能阻止数据竞争,让并发编程不再提心吊胆。

Rust vs 其他语言对比

特性RustC/C++GoJava
内存安全✅ 编译期保证❌ 手动管理✅ GC✅ GC
零成本抽象⚠️ 部分⚠️ 有运行时开销❌ JIT开销
无GC❌ 有GC❌ 有GC
并发安全✅ 编译期检查❌ 运行时出错⚠️ 运行时检查⚠️ 运行时检查
运行时开销极小极小中等较大

🚀 Rust的应用领域

📦 安装Rust

Rust使用rustup作为版本管理工具,它是安装和管理Rust的标准方式。

Linux/macOS安装

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

安装完成后,需要加载环境变量:

source $HOME/.cargo/env

Windows安装

访问 https://rustup.rs 下载 rustup-init.exe 并运行。

验证安装

# 检查rustc版本
rustc --version
# 检查cargo版本
cargo --version
# 检查rustup版本
rustup --version
rustc 1.95.0 (59807616e 2026-04-14) cargo 1.95.0 (f2d3ce0bd 2026-03-21) rustup 1.28.1

✅ 验证通过

💡 提示:如果命令找不到,请确认$HOME/.cargo/bin在PATH中。重启终端通常可以解决。

配置国内镜像源(中国大陆用户推荐)

编辑$HOME/.cargo/config.toml

[source.crates-io]
replace-with = "ustc"

[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"

🔧 Rust工具链概览

rustc —— Rust编译器

.rs源文件编译为可执行文件。日常开发中通常通过cargo调用,很少直接使用。

rustc main.rs -o main

cargo —— Rust构建工具和包管理器

Cargo是Rust生态的核心,集成了项目创建、编译、测试、依赖管理、发布等功能。

cargo new my_project    # 创建新项目
cargo build              # 编译项目
cargo run                # 编译并运行
cargo test               # 运行测试
cargo check              # 快速检查(不生成二进制)
cargo add serde          # 添加依赖
cargo update             # 更新依赖

rustfmt —— 代码格式化

cargo fmt               # 自动格式化代码

clippy —— 代码检查工具

cargo clippy            # 运行代码检查

👋 第一个Rust程序

方式一:使用rustc直接编译

创建文件hello.rs

// hello.rs - 第一个Rust程序
fn main() {
    println!("Hello, Rust! 🦀");
    
    // 变量绑定
    let language = "Rust";
    let year = 2010;
    
    println!("{}诞生于{}年", language, year);
    
    // 格式化输出
    println!("Rust的吉祥物是Ferris 🦀");
    println!("十进制: {} 八进制: {:#o} 十六进制: {:#x}", 255, 255, 255);
}
$ rustc hello.rs -o hello && ./hello Hello, Rust! 🦀 Rust诞生于2010年 Rust的吉祥物是Ferris 🦀 十进制: 255 八进制: 0o377 十六进制: 0xff

✅ 验证通过

方式二:使用Cargo项目

cargo new hello_rust
cd hello_rust

Cargo生成的项目结构:

hello_rust/
├── Cargo.toml        # 项目配置文件
└── src/
    └── main.rs       # 源代码入口

Cargo.toml内容:

[package]
name = "hello_rust"
version = "0.1.0"
edition = "2024"

[dependencies]

编辑src/main.rs

use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    // 基础输出
    println!("=== 我的第一个Cargo项目 ===");
    println!("Hello, Rust! 🦀");
    
    // 获取当前时间戳
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    
    println!("当前Unix时间戳: {}", timestamp);
    
    // 条件判断
    if timestamp % 2 == 0 {
        println!("时间戳是偶数");
    } else {
        println!("时间戳是奇数");
    }
    
    // 循环
    println!("\n倒计时:");
    for i in (1..=5).rev() {
        println!("  {}...", i);
    }
    println!("🚀 Rust,起飞!");
}
$ cargo run Compiling hello_rust v0.1.0 (/root/hello_rust) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.5s Running `target/debug/hello_rust` === 我的第一个Cargo项目 === Hello, Rust! 🦀 当前Unix时间戳: 1776748860 时间戳是偶数 倒计时: 5... 4... 3... 2... 1... 🚀 Rust,起飞!

✅ 验证通过

🧪 println!宏详解

println!是Rust的宏(macro),不是函数。宏名以!结尾是Rust的惯例。

// 基本用法
println!("Hello");                    // 输出: Hello
println!("{} {}", "Hello", "Rust");   // 位置参数
println!("{0} {1} {0}", "A", "B");    // 命名位置参数 → A B A

// 命名参数
println!("{name}的版本是{version}", name="Rust", version="1.95");

// 格式化控制
println!("浮点数: {:.2}", 3.14159);    // 保留2位小数 → 3.14
println!("右对齐: {:>10}", "Rust");     // 宽度10右对齐
println!("左对齐: {:<10}!", "Rust");    // 宽度10左对齐
println!("居中:   {:^10}", "Rust");     // 宽度10居中
println!("补零:   {:05}", 42);          // 5位补零 → 00042

// 进制
println!("二进制: {:b}", 10);           // → 1010
println!("八进制: {:o}", 10);           // → 12
println!("十六进制: {:x}", 255);        // → ff
println!("十六进制: {:X}", 255);        // → FF

// 调试格式
let v = vec![1, 2, 3];
println!("调试: {:?}", v);              // → [1, 2, 3]
println!("漂亮调试: {:#?}", v);         // 多行格式化

📐 Rust程序基本结构

// 这是行注释
/* 这是
   块注释 */

/// 这是文档注释(用于生成文档)
/// 描述函数的功能
fn my_function(x: i32) -> i32 {
    x * 2  // 最后一个表达式即为返回值(无分号)
}

// 入口函数
fn main() {
    // 语句以分号结尾
    let result = my_function(21);
    println!("21 * 2 = {}", result);
}
💡 关键概念:Rust中表达式和语句的区别非常重要。表达式有返回值,语句没有。最后一个表达式不加;就作为返回值。

🏷️ Rust Edition(版本)

Rust每3年发布一个Edition,目前有:2015、2018、2021、2024。Edition是语法和语义的版本,不影响编译后的二进制兼容性。

// Cargo.toml中指定edition
[package]
edition = "2024"

📝 练习

练习1:环境验证

在终端运行以下命令,确认所有工具可用:

rustc --version
cargo --version
rustup --version
rustfmt --version
cargo clippy --version

练习2:个性化问候

创建一个Cargo项目,编写程序实现:

练习3:格式化输出

编写程序,用不同的格式化方式输出数字42:

练习4:探索Cargo

尝试以下Cargo命令,观察输出:

cargo new explore
cd explore
cargo check
cargo build
cargo build --release
cargo run

🏆 本课成就

🔒 下一课解锁:变量与数据类型 —— 深入Rust的类型系统

🔬 Rust编译器详解

// rustc编译选项
// rustc --edition 2024 --release -C opt-level=3 main.rs

// 常用编译属性
#![allow(unused_variables)]   // 允许未使用变量
#![warn(missing_docs)]         // 警告缺少文档
#![feature(box_syntax)]        // 启用实验性特性(仅nightly)

// 条件编译
#[cfg(target_os = "linux")]
fn platform_specific() { println!("运行在Linux上"); }

#[cfg(target_os = "windows")]
fn platform_specific() { println!("运行在Windows上"); }

#[cfg(target_arch = "x86_64")]
fn arch_info() { println!("64位x86架构"); }

fn main() {
    platform_specific();
    arch_info();
    println!("指针宽度: {}位", std::mem::size_of::() * 8);
    println!("Rust版本: {}", env!("RUSTC_BOOTSTRAP").split('.').next().unwrap_or("?"));
}

🎯 Cargo进阶用法

// Cargo.toml完整配置
// [package]
// name = "my_app"
// version = "0.1.0"
// authors = ["Your Name "]
// edition = "2024"
// description = "A sample Rust application"
// license = "MIT"
// repository = "https://github.com/you/my_app"
//
// [dependencies]
// serde = { version = "1.0", features = ["derive"] }
//
// [dev-dependencies]
// assert_cmd = "2.0"
//
// [build-dependencies]
// cc = "1.0"
//
// [features]
// default = ["feature1"]
// feature1 = []
// feature2 = ["dep:serde"]
//
// [profile.dev]
// opt-level = 0
// debug = true
//
// [profile.release]
// opt-level = 3
// lto = true
// codegen-units = 1
// strip = true

// cargo常用命令速查
// cargo init          - 在当前目录初始化
// cargo new name      - 创建新项目
// cargo build         - 编译(debug模式)
// cargo build --release - 编译(release模式)
// cargo run           - 编译并运行
// cargo check         - 快速检查(不生成二进制)
// cargo test          - 运行测试
// cargo doc           - 生成文档
// cargo doc --open    - 生成并打开文档
// cargo clean         - 清理构建产物
// cargo update        - 更新依赖
// cargo tree          - 查看依赖树
// cargo clippy        - 代码检查
// cargo fmt           - 格式化代码
// cargo publish       - 发布到crates.io
// cargo install crate - 安装二进制crate

🌐 Rust生态系统概览

领域推荐crate说明
序列化serdeJSON/YAML/TOML等统一接口
HTTP客户端reqwest异步HTTP客户端
Web框架axum/actix-web高性能Web服务
数据库sqlx/diesel异步/编译期SQL检查
CLIclap命令行参数解析
日志tracing/log结构化日志
错误处理anyhow/thiserror应用/库错误处理
正则regex高性能正则引擎
随机数rand随机数生成
时间chrono日期时间处理