NexaGrid技术博客

NexaGrid技术博客

五、Rust从基础到实战应用(所有权系统)

2
2025-07-18
五、Rust从基础到实战应用(所有权系统)

所有权系统是Rust语言最基础、最独特,也是最重要的特性。所有权系统让Rust无需垃圾回收机制就可保障内存安全与运行效率。所有权系统包括所有权,借用,生命周期。

所有权

Rust所有权机制的核心有3点:

  1. 每个值都有一个被称为其所有者的变量,所有者拥有这块内存空间的释放和读写权限。

  2. 每个值在任意时刻有且仅有一个所有者。

  3. 当所有者离开作用域,变量的所有者离开后,内存被释放。

变量绑定

当变量和值发生绑定的时候,这个变量成为了这个值对应内存空间的所有者。

fn foo() {
  let s = String::from("hello,world"); // s有效
} // s离开作用域,s无效,内存空间被释放

所有权转移

所有权转移发生在三种地方:1. 赋值 2. 传参 3. 返回。正如我们说的一份值任意时刻有且仅有一个所有者,而所有权才有读写他的权限。当所有权转移后,前任不能使用他了(编译器会报错)。

1. 变量赋值

fn main(){
  let x = 5;
  let y = x;
  println!("x: {}, y: {}", x, y);

  let s1 = String::from("hello,world!");
  let s2 = s1;  // s1绑定的值的所有权转移给s2
  // println!("s1: {}, s2: {}", s1, s2); // 取消注释,这里就会报错。value borrowed here after move
}
  

2. 传参

fn main() {
  let s = String::from("hello,world!");  // s有效
  take_ownership(s);  // s所有权转移给函数参数
}

fn take_ownership(str: String) {
  println!("{}", str);
}

3. 返回

fn main() {
  let s = give_ownership(s);  // give_ownership的返回值的所有权转移给s
}

fn give_ownership() -> String {
  let str = String::from("hello");  // str有效
  str
}

当值是栈上数据的时候, 但是所有权不转移。

借用

生命周期