所有权

所有变量绑定都有一个有效的“作用域”,使用 超出其作用域的变量是错误的:

  1. struct Point(i32, i32);
  2. fn main() {
  3. {
  4. let p = Point(3, 4);
  5. println!("x: {}", p.0);
  6. }
  7. println!("y: {}", p.1);
  8. }

We say that the variable owns the value. Every Rust value has precisely one owner at all times.

At the end of the scope, the variable is dropped and the data is freed. A destructor can run here to free up resources.

This slide should take about 5 minutes.

熟悉垃圾回收实现的学生知道,垃圾回收器从一组 “根”开始查找所有可访问内存。Rust 的 “单一所有者”原则与此类似。