From 2e59d297964273304263166f981256287a1f1f28 Mon Sep 17 00:00:00 2001 From: Allan Downey Date: Sat, 26 Mar 2022 10:20:55 +0800 Subject: [PATCH] =?UTF-8?q?fix(borrowing):=20=E4=BF=AE=E6=94=B9=E7=AB=A0?= =?UTF-8?q?=E8=8A=82=E6=A0=87=E9=A2=98=E5=AD=97=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/basic/ownership/borrowing.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/basic/ownership/borrowing.md b/src/basic/ownership/borrowing.md index 6abe055f..e89940bc 100644 --- a/src/basic/ownership/borrowing.md +++ b/src/basic/ownership/borrowing.md @@ -4,7 +4,7 @@ Rust 通过 `借用(Borrowing)` 这个概念来达成上述的目的,**获取变量的引用,称之为借用(borrowing)**。正如现实生活中,如果一个人拥有某样东西,你可以从他那里借来,当使用完毕后,也必须要物归原主。 -### 引用与解引用 +## 引用与解引用 常规引用是一个指针类型,指向了对象存储的内存地址。在下面代码中,我们创建一个 `i32` 值的引用 `y`,然后使用解引用运算符来解出 `y` 所使用的值: @@ -35,7 +35,7 @@ error[E0277]: can't compare `{integer}` with `&{integer}` 不允许比较整数与引用,因为它们是不同的类型。必须使用解引用运算符解出引用所指向的值。 -### 不可变引用 +## 不可变引用 下面的代码,我们用 `s1` 的引用作为参数传递给 `calculate_length` 函数,而不是把 `s1` 的所有权转移给该函数: @@ -102,7 +102,7 @@ error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` ref 正如变量默认不可变一样,引用指向的值默认也是不可变的,没事,来一起看看如何解决这个问题。 -### 可变引用 +## 可变引用 只需要一个小调整,即可修复上面代码的错误: @@ -118,9 +118,9 @@ fn change(some_string: &mut String) { } ``` -首先,声明 `s` 是可变类型,其次创建一个可变的引用 `&mut s` 和接受可变引用的函数 `some_string: &mut String`。 +首先,声明 `s` 是可变类型,其次创建一个可变的引用 `&mut s` 和接受可变引用参数 `some_string: &mut String` 的函数。 -##### 可变引用同时只能存在一个 +#### 可变引用同时只能存在一个 不过可变引用并不是随心所欲、想用就用的,它有一个很大的限制: **同一作用域,特定数据只能有一个可变引用**: @@ -173,7 +173,7 @@ let mut s = String::from("hello"); let r2 = &mut s; ``` -##### 可变引用与不可变引用不能同时存在 +#### 可变引用与不可变引用不能同时存在 下面的代码会导致一个错误: @@ -310,7 +310,6 @@ fn no_dangle() -> String { - 同一时刻,你只能拥有要么一个可变引用, 要么任意多个不可变引用 - 引用必须总是有效的 - ## 课后练习 -> [Rust By Practice](https://zh.practice.rs/ownership/borrowing.html),支持代码在线编辑和运行,并提供详细的[习题解答](https://github.com/sunface/rust-by-practice)。 \ No newline at end of file +> [Rust By Practice](https://zh.practice.rs/ownership/borrowing.html),支持代码在线编辑和运行,并提供详细的[习题解答](https://github.com/sunface/rust-by-practice)。