rust ownership - WinChua/blog GitHub Wiki

  • 三个规则:

Each value in Rust has an owner. // value 可以理解为一段内存区域

There can only be one owner at a time. // 同一时间内, 一段内存区域只能有一个owner

When the owner goes out of scope, the value will be dropped. // rust 在变量离开作用域的时候自动调用drop trait

  • String 为例子
let x = String::from("hello");
let y = x; // x的ownership move 到 y, 之后使用x是非法的, rust会阻止编译

let y = x; 这个语句执行的时候, stack上复制了, String结构中的len, ptr, cap, 其中ptr指向了heap上的字符串内容地址

如果想要保留原来的x,需要使用deepcopy, let y = x.clone();

  • Copy trait 对于其他一些可以简单在stack上进行复制的类型来说, 他们实现了Copy trait, 在赋值的时候, 原变量的ownership不会move, 只会在stack上进行内存复制形成新的变量 常见的实现了Copy trait的类型: 所有整数类型, 布尔类型, 浮点数类型, 字符, tuples(如果所有的子type都实现了Copy,eg: (i32, i32), 而(i32, String) 就没有Copy)

reference && borrowing

  • 对于一个变量, 同一时间, 最多只能有一个可变的reference, 0个不可变reference 或者 0个可变reference, 多个不变reference;
  • reference 必须是valid的