Rust 是一门注重内存安全、性能和并发性的系统编程语言。以下是其核心语法的扩展介绍,涵盖更多细节和实用特性,适合初学者快速了解并深入掌握。

1. 变量与常量

  • 变量:使用 let 声明,默认不可变。使用 mut 允许修改。变量可以被遮蔽(重新声明)。
    let x = 5;
    let x = x + 1; // 遮蔽,创建新变量
    let mut y = 10;
    y = 15;
  • 常量:使用 const 声明,需指定类型,全局作用域,值在编译时确定。
    const MAX_VALUE: u32 = 100_000; // 下划线提高数字可读性
  • 静态变量:使用 static 声明,生命周期贯穿程序运行。
    static GREETING: &str = "Hello, Rust!";

2. 数据类型

  • 标量类型
    • 整数:有符号 (i8, i16, i32, i64, i128),无符号 (u8, u16, u32, u64, u128),以及 isize/usize(与系统架构相关)。
    • 浮点数:f32, f64
    • 布尔:bool (true, false)。
    • 字符:char (Unicode,单引号,如 '😊')。
  • 复合类型
    • 元组:固定长度,异构类型,可通过 .0, .1 访问或解构。
      let tup: (i32, f64, char) = (500, 6.4, 'z');
      let (x, y, z) = tup; // 解构
    • 数组:固定长度,同构类型,栈分配。
      let arr: [i32; 5] = [1, 2, 3, 4, 5];
      let first = arr[0];
    • 向量:动态数组,使用标准库 Vec<T>,堆分配。
      let mut v = vec![1, 2, 3];
      v.push(4);

3. 函数

  • 函数使用 fn 定义,参数和返回值需显式指定类型。无返回值时省略 ->
    fn add(a: i32, b: i32) -> i32 {
        a + b // 表达式返回值,无需 return
    }
  • 发散函数:永不返回,使用 ! 作为返回类型(如 panic!)。
    fn diverge() -> ! {
        panic!("This function never returns!");
    }

4. 控制流

  • 条件语句
    • if 支持表达式风格返回值,无需三元运算符。
      let number = 7;
      let result = if number > 0 { "positive" } else { "non-positive" };
    • 条件必须是 bool 类型。
  • 循环
    • loop:无限循环,可用 break 返回值。
      let mut counter = 0;
      let result = loop {
          counter += 1;
          if counter == 10 {
              break counter * 2;
          }
      };
    • while:条件循环。
      while counter < 15 {
          counter += 1;
      }
    • for:常用于迭代器或范围。
      for i in 0..5 { // 包含 0,不包含 5
          println!("i: {}", i);
      }

5. 所有权与借用

  • 所有权:每个值有唯一所有者,离开作用域时释放。移动后原变量失效。
    let s1 = String::from("hello");
    let s2 = s1; // s1 失效
    // println!("{}", s1); // 错误:s1 已移动
  • 借用:使用 & 创建不可变引用,&mut 创建可变引用。同一时间只能有一个可变引用或多个不可变引用。
    let mut s = String::from("hello");
    let r1 = &s; // 不可变借用
    let r2 = &mut s; // 可变借用
    // println!("{}", r1); // 错误:不可同时有可变和不可变借用
  • 复制:实现了 Copy trait 的类型(如基本类型)不会移动。
    let x = 5;
    let y = x; // 复制,x 仍有效

6. 结构体与枚举

  • 结构体
    • 命名结构体:
      struct Rectangle {
          width: u32,
          height: u32,
      }
      let rect = Rectangle { width: 30, height: 50 };
    • 元组结构体:
      struct Color(u8, u8, u8);
      let black = Color(0, 0, 0);
    • 方法:使用 impl 定义。
      impl Rectangle {
          fn area(&self) -> u32 {
              self.width * self.height
          }
      }
  • 枚举:支持复杂数据结构,常与 match 结合。
    enum Message {
        Quit,
        Move { x: i32, y: i32 },
        Write(String),
    }

7. 模式匹配

  • match:穷尽匹配,必须覆盖所有情况。
    let num = Some(4);
    match num {
        Some(x) if x % 2 == 0 => println!("Even: {}", x),
        Some(x) => println!("Odd: {}", x),
        None => println!("None"),
    }
  • if let:简化单一模式匹配。
    if let Some(x) = num {
        println!("Value: {}", x);
    }

8. 错误处理

  • Option:处理可能为空的值 (Some(T)None)。
    let opt: Option<i32> = Some(5);
    let value = opt.unwrap_or(0); // 解包或提供默认值
  • Result:处理可能出错的操作 (Ok(T)Err(E))。
    fn divide(a: i32, b: i32) -> Result<i32, String> {
        if b == 0 {
            Err(String::from("Divide by zero"))
        } else {
            Ok(a / b)
        }
    }
    let result = divide(10, 2).expect("Division failed"); // 成功返回 5
  • ? 运算符:简化错误传播。
    fn try_divide() -> Result<i32, String> {
        let result = divide(10, 0)?;
        Ok(result)
    }

9. 模块系统

  • 使用 mod 定义模块,pub 控制可见性,use 引入路径。
    mod front_of_house {
        pub mod hosting {
            pub fn add_to_waitlist() {}
        }
    }
    use crate::front_of_house::hosting;
    hosting::add_to_waitlist();
  • 文件系统模块:mod 声明会加载同名文件或目录中的代码。

10. 集合类型

  • Vec:动态数组。
    let mut v = Vec::new();
    v.push(1);
  • HashMap:键值对集合。
    use std::collections::HashMap;
    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);

11. 泛型与 trait

  • 泛型:提高代码复用性。
    fn largest<T: PartialOrd>(list: &[T]) -> &T {
        &list[0]
    }
  • trait:定义共享行为,类似接口。
    trait Summary {
        fn summarize(&self) -> String;
    }
    struct Article {
        content: String,
    }
    impl Summary for Article {
        fn summarize(&self) -> String {
            format!("Article: {}", self.content)
        }
    }

12. 生命周期

  • 确保引用有效,生命周期注解用 'a 表示。
    fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
        if x.len() > y.len() { x } else { y }
    }

13. 并发

  • 线程:使用 std::thread
    use std::thread;
    let handle = thread::spawn(|| {
        println!("Running in a thread!");
    });
    handle.join().unwrap();
  • 消息传递:通过通道 (mpsc)。
    use std::sync::mpsc;
    let (tx, rx) = mpsc::channel();
    tx.send(42).unwrap();
    println!("Received: {}", rx.recv().unwrap());
  • 共享状态:使用 MutexArc
    use std::sync::{Arc, Mutex};
    let counter = Arc::new(Mutex::new(0));

14. 常用宏

  • println!, format!:格式化输出。
  • vec!:快速创建向量。
  • panic!:触发程序崩溃。
  • todo!:标记未实现代码。
    let v = vec![1, 2, 3];
    println!("{:?}", v);

15. 智能指针

  • Box:堆分配。
    let b = Box::new(5);
  • Rc:引用计数,单线程共享。
  • Arc:原子引用计数,多线程共享。