chapter 4 ownership
4.1 what is ownership
ownership rule
- Each value in Rust has a variable that’s called its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
在rust中,当heap中的值发生,赋值、调用、返回时,都会发生所有权的“转移”
1 2 3 4 5 6 7 8 9 10 11
| let s1 = String::from("hello"); let s2 = s1;
let s1 = String::from("hello"); takes_ownership(s1);
let s2 = String::from("hello"); let s3 = takes_and_gives_back(s2);
|
- but It’s quite annoying that anything we pass in also needs to be passed back if we want to use it again!
4.2 References and Borrowing
reference allow refer to some value without taking ownership.
1 2 3 4 5 6 7 8 9 10 11
| fn main() { let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len); }
fn calculate_length(s: &String) -> usize { s.len() }
|
mutable reference
1 2 3 4 5 6 7 8 9
| fn main() { let mut s = String::from("hello");
change(&mut s); }
fn change(some_string: &mut String) { some_string.push_str(", world"); }
|
rule of reference
- 在任何时间,你只能拥有一个可变引用,或者,多个不可变引用。
- 引用必须是存在的,不允许悬挂的引用(dangling reference)。
4.3 Slice Type 切片
切片是另一种没有所有权的数据类型。切片允许你引用一个集合的连续元素。
1 2 3
| let s = String::from("hello world"); let hello = &s[0..5]; let world = &s[6..11];
|
- 变量s的类型是&str,等号右边称为”字符串字面量”;字符串是硬编码(hardcoding)在代码中,既不存在stack也不在heap,而是在程序的二进制代码中,即s是指向二进制代码中一段位置的一个切片。