← 返回首页
叶知秋
2026年1月10日 10:00

Rust 入门:所有权与借用

所有权规则

  1. Rust 中的每个值都有一个称为其所有者的变量
  2. 同一时间只能有一个所有者
  3. 当所有者离开作用域,值将被丢弃
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;             // s1 的所有权转移给 s2
    println!("{}", s2);      // 正常
}

借用

引用允许你使用值而不获取其所有权:

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);
    println!("'{}' 的长度是 {}", s1, len);
}

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

生命周期

生命周期确保引用始终有效。大多数情况下 Rust 可以自动推断,复杂场景需要手动标注。

Rust内存安全所有权