# Understanding Ownership

Rust中最独特的性质，保证内存使用的安全性（不需要GC）。

Ownership is Rust’s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector.

## What Is Ownership

The way to memory management:

1. Use Garbage Collection(GC) that constantly looks for no longer used memory as the program runs.
2. Programmer must explecitly allocate and free the memory.
3. (Rust) Memroy is managed through a system of ownership with a set fo rules that the compiler checks at compile time. None of the ownership features slow down your program while it’s running.

### Ownership Rules

Keep these rules in mind!

• 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.

### Memroy and Allocation

In the case of a string literal, we know the contents at compile time, so the text is hardcoded directly into the final executable. This is why string literals are fast and efficient. But these properties only come from the string literal’s immutability. Unfortunately, we can’t put a blob of memory into the binary for each piece of text whose size is unknown at compile time and whose size might change while running the program.

With the String type, in order to support a mutable, growable piece of text, we need to allocate an amount of memory on the heap, unknown at compile time, to hold the contents. This means:

• The memory must be requested from the memory allocator at runtime.(Construct function)
• We need a way of returning this memory to the allocator when we’re done with our String.(Out of scope, special function drop)

#### Ways Variables and Data Interact: Move

shallow copy? deep copy? Rust prefers move.

shallow copy + invalidate

#### Ways Variables and Data Interact: Clone

If we do want to deeply copy the heap data of the String, not just the stack data, we can use a common method called clone.

#### Stack-Only Data: Copy

But this code seems to contradict what we just learned: we don’t have a call to clone, but x is still valid and wasn’t moved into y.

Types that have known size at compile time are stored entirely on the stack.

Rust 有一个叫做 Copy trait 的特殊注解，可以用在类似整型这样的存储在栈上的类型上（第十章详细讲解 trait）。如果一个类型实现了 Copy trait，那么一个旧的变量在将其赋值给其他变量后仍然可用。Rust 不允许自身或其任何部分实现了 Drop trait 的类型使用 Copy trait。如果我们对其值离开作用域时需要特殊处理的类型使用 Copy 注解，将会出现一个编译时错误。要学习如何为你的类型添加 Copy 注解以实现该 trait，请阅读附录 C 中的 “可派生的 trait”。

• 所有整数类型，比如 u32
• 布尔类型，bool，它的值是 truefalse。
• 所有浮点数类型，比如 f64
• 字符类型，char
• 元组，当且仅当其包含的类型也都实现 Copy 的时候。比如，(i32, i32) 实现了 Copy，但 (i32, String) 就没有。

### Ownership and Functions

Taking ownership and then returning ownership with every function is a bit tedious. What if we want to let a function use a value but not take ownership?

## References and Borrowing

Refer but not own

The &s1 syntax lets us create a reference that refers to the value of s1 but does not own it. Because it does not own it, the value it points to will not be dropped when the reference goes out of scope.

When functions have references as parameters instead of the actual values, we won’t need to return the values in order to give back ownership, because we never had ownership. 这样就避免了每次都需要通过元组来取回 ownership。称为Borrowing

references 同variables，默认也是immutable的。

### Mutable References

First, we had to change s to be mut（否则编译报错 E0596”:cannot borrow s as mutable）. Then we had to create a mutable reference with &mut s（reference 默认也是immutable） and accept a mutable reference with some_string: &mut String.

One big restriction: you can have only one mutable reference to a particular piece of data in a particular scope.

### Dangling References

C/C++ 悬挂指针问题

In Rust, by contrast, the compiler guarantees that references will never be dangling references: if you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does.

Danger case:

Ownership move:

### The Rules of References

Let’s recap what we’ve discussed about references:

• At any given time, you can have either one mutable reference or any number of immutable references.
• References must always be valid.

Next, we’ll look at a different kind of reference: slices.

## The Slice Type

Getting starting/ending index from String (not tied to String state)

### String slices

With all this information in mind, let’s rewrite first_word to return a slice. The type that signifies “string slice” is written as &str:

### String Literals Are Slices

Recall that we talked about string literals being stored inside the binary. Now that we know about slices, we can properly understand string literals:

s的类型是&str，这也可以解释为什么string literals都是immutable的，&str是immutable引用。

### String Slices as parameters

More experienced Rustaceans prefer:

Deref coericion强制类型转换。