rust ownership

2021-05-29  本文已影响0人  戈壁堂

所有权(系统)是 Rust 最为与众不同的特性,它让 Rust 无需垃圾回收(garbage collector)即可保障内存安全。相关功能包括:借用、slice 以及 Rust 如何在内存中布局数据。

程序管理使用计算机内存的方式:

首先要了解“栈(Stack)与堆(Heap)”的四个主要区别——

当代码调用一个函数时,传递给函数的值(包括可能指向堆上数据的指针)和函数的局部变量被压入栈中。当函数结束时,这些值被移出栈。

所有权意义:(管理堆数据)

所有权规则:

  1. Rust 中的每一个值都有一个被称为其 所有者(owner)的变量。Each value in Rust has a variable that’s called its owner.
  2. 值在任一时刻有且只有一个所有者。There can only be one owner at a time.
  3. 当所有者(变量)离开作用域,这个值将被丢弃。When the owner goes out of scope, the value will be dropped.
let s1 = String::from("hello");
let s2 = s1;

println!("{}, world!", s1); // 无效
println!("{}, world!", s2);
上一篇 下一篇

猜你喜欢

热点阅读