目录

Rust语言入门指南

Rust 是一门注重安全、并发和性能的系统编程语言,连续多年成为开发者最喜爱的语言。

为什么选择 Rust?

  • 内存安全:所有权系统在编译时保证内存安全,无需垃圾回收
  • 零成本抽象:高级特性不带来运行时开销
  • fearless 并发:编译器防止数据竞争
  • 优秀的工具链:Cargo 包管理器让开发体验极佳

安装与 Hello World

bash
# 安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 创建项目
cargo new hello_rust
cd hello_rust
cargo run
rust
fn main() {
    println!("Hello, Rust!");
}

所有权系统

所有权是 Rust 最核心的特性:

rust
fn main() {
    // s 拥有字符串
    let s = String::from("hello");

    // 所有权转移给 s2,s 不再有效
    let s2 = s;

    // println!("{}", s); // 编译错误!s 已被移动

    // 借用:不转移所有权
    let s3 = String::from("world");
    let len = calculate_length(&s3);
    println!("'{}' 的长度是 {}", s3, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

结构体与方法

rust
struct User {
    username: String,
    email: String,
    age: u32,
    active: bool,
}

impl User {
    // 关联函数(类似构造函数)
    fn new(username: String, email: String) -> Self {
        User {
            username,
            email,
            age: 0,
            active: true,
        }
    }

    // 方法
    fn is_adult(&self) -> bool {
        self.age >= 18
    }
}

fn main() {
    let user = User::new("star".to_string(), "star@example.com".to_string());
    println!("用户名: {}", user.username);
}

枚举与模式匹配

rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn process(msg: Message) {
    match msg {
        Message::Quit => println!("退出"),
        Message::Move { x, y } => println!("移动到 ({}, {})", x, y),
        Message::Write(text) => println!("写入: {}", text),
        Message::ChangeColor(r, g, b) => println!("颜色: ({}, {}, {})", r, g, b),
    }
}

错误处理

rust
use std::fs::File;
use std::io::Read;

fn read_file(path: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

fn main() {
    match read_file("config.toml") {
        Ok(content) => println!("{}", content),
        Err(e) => eprintln!("读取失败: {}", e),
    }
}

Cargo 依赖管理

toml
[package]
name = "my_app"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

总结

Rust 的学习曲线确实较陡,特别是所有权和生命周期概念。但一旦掌握,你将获得内存安全和高性能的双重保障。建议从官方的 Rust Book 开始,配合 rustlings 练习逐步入门。