引用与借用
在 Listing 4-5 中的元组代码的问题在于,我们必须将 String
返回给调用函数,以便在调用 calculate_length
后仍然可以使用 String
,因为 String
被移动到了 calculate_length
中。相反,我们可以提供一个对 String
值的引用。引用类似于指针,它是一个地址,我们可以通过它访问存储在该地址的数据;这些数据由其他变量拥有。与指针不同的是,引用在其生命周期内保证指向某个特定类型的有效值。
下面是如何定义和使用一个 calculate_length
函数,该函数以引用作为参数,而不是获取值的所有权:
fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{s1}' is {len}."); } fn calculate_length(s: &String) -> usize { s.len() }
首先,注意变量声明和函数返回值中的所有元组代码都消失了。其次,注意我们传递 &s1
给 calculate_length
,并且在函数定义中,我们使用 &String
而不是 String
。这些 &
符号表示引用,它们允许你引用某个值而不获取其所有权。图 4-6 描绘了这一概念。
图 4-6: &String s
指向 String s1
的示意图
注意:使用
&
进行引用的相反操作是解引用,它通过解引用操作符*
完成。我们将在第 8 章看到解引用操作符的一些用法,并在第 15 章详细讨论解引用。
让我们仔细看看这里的函数调用:
fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{s1}' is {len}."); } fn calculate_length(s: &String) -> usize { s.len() }
&s1
语法让我们创建一个引用,它引用 s1
的值但不拥有它。因为引用不拥有它,所以当引用停止使用时,它指向的值不会被丢弃。
同样,函数的签名使用 &
来表明参数 s
的类型是一个引用。让我们添加一些解释性注释:
fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{s1}' is {len}."); } fn calculate_length(s: &String) -> usize { // s is a reference to a String s.len() } // Here, s goes out of scope. But because s does not have ownership of what // it refers to, the value is not dropped.
变量 s
的有效范围与任何函数参数的范围相同,但当 s
停止使用时,引用指向的值不会被丢弃,因为 s
没有所有权。当函数使用引用作为参数而不是实际值时,我们不需要返回值来归还所有权,因为我们从未拥有过所有权。
我们将创建引用的行为称为借用。就像在现实生活中,如果一个人拥有某样东西,你可以从他们那里借用它。当你用完时,你必须归还它。你不拥有它。
那么,如果我们尝试修改我们借用的东西会发生什么?试试 Listing 4-6 中的代码。剧透警告:它不会工作!
fn main() {
let s = String::from("hello");
change(&s);
}
fn change(some_string: &String) {
some_string.push_str(", world");
}
以下是错误信息:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
--> src/main.rs:8:5
|
8 | some_string.push_str(", world");
| ^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference
|
7 | fn change(some_string: &mut String) {
| +++
For more information about this error, try `rustc --explain E0596`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
正如变量默认是不可变的一样,引用也是不可变的。我们不允许修改我们引用的东西。
可变引用
我们可以通过一些小的调整来修复 Listing 4-6 中的代码,以允许我们修改借用的值,使用可变引用:
fn main() { let mut s = String::from("hello"); change(&mut s); } fn change(some_string: &mut String) { some_string.push_str(", world"); }
首先我们将 s
改为 mut
。然后我们在调用 change
函数时使用 &mut s
创建一个可变引用,并更新函数签名以接受一个可变引用 some_string: &mut String
。这使得 change
函数将改变它借用的值变得非常清晰。
可变引用有一个很大的限制:如果你有一个值的可变引用,你就不能有其他对该值的引用。尝试创建两个对 s
的可变引用的代码将失败:
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{}, {}", r1, r2);
}
以下是错误信息:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0499]: cannot borrow `s` as mutable more than once at a time
--> src/main.rs:5:14
|
4 | let r1 = &mut s;
| ------ first mutable borrow occurs here
5 | let r2 = &mut s;
| ^^^^^^ second mutable borrow occurs here
6 |
7 | println!("{}, {}", r1, r2);
| -- first borrow later used here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
这个错误说明这段代码无效,因为我们不能同时多次借用 s
作为可变引用。第一次可变借用是在 r1
中,并且必须持续到它在 println!
中使用为止,但在创建该可变引用和它的使用之间,我们尝试在 r2
中创建另一个可变引用,它借用了与 r1
相同的数据。
防止同时存在多个对同一数据的可变引用的限制允许进行改变,但以非常受控的方式进行。这是新 Rust 程序员经常遇到的问题,因为大多数语言允许你随时进行改变。拥有这种限制的好处是,Rust 可以在编译时防止数据竞争。数据竞争类似于竞态条件,当以下三种行为发生时就会发生:
- 两个或更多指针同时访问同一数据。
- 至少有一个指针用于写入数据。
- 没有用于同步数据访问的机制。
数据竞争会导致未定义行为,并且在运行时尝试追踪它们时可能难以诊断和修复;Rust 通过拒绝编译带有数据竞争的代码来防止这个问题!
一如既往,我们可以使用花括号创建一个新的作用域,允许多个可变引用,只是不能同时存在:
fn main() { let mut s = String::from("hello"); { let r1 = &mut s; } // r1 goes out of scope here, so we can make a new reference with no problems. let r2 = &mut s; }
Rust 对结合可变和不可变引用执行了类似的规则。这段代码会导致错误:
fn main() {
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
let r3 = &mut s; // BIG PROBLEM
println!("{}, {}, and {}", r1, r2, r3);
}
以下是错误信息:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:6:14
|
4 | let r1 = &s; // no problem
| -- immutable borrow occurs here
5 | let r2 = &s; // no problem
6 | let r3 = &mut s; // BIG PROBLEM
| ^^^^^^ mutable borrow occurs here
7 |
8 | println!("{}, {}, and {}", r1, r2, r3);
| -- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
哇!我们也不能在有一个不可变引用的情况下拥有一个对同一值的可变引用。
不可变引用的用户不希望值突然在他们下面改变!然而,允许多个不可变引用,因为只读取数据的人没有能力影响其他人对数据的读取。
注意,引用的作用域从它被引入的地方开始,一直持续到最后一次使用该引用。例如,这段代码将编译,因为不可变引用的最后一次使用是在 println!
中,在引入可变引用之前:
fn main() { let mut s = String::from("hello"); let r1 = &s; // no problem let r2 = &s; // no problem println!("{r1} and {r2}"); // Variables r1 and r2 will not be used after this point. let r3 = &mut s; // no problem println!("{r3}"); }
不可变引用 r1
和 r2
的作用域在它们最后一次使用的 println!
之后结束,这是在创建可变引用 r3
之前。这些作用域不重叠,所以这段代码是允许的:编译器可以判断出在作用域结束之前,引用不再被使用。
尽管借用错误有时可能令人沮丧,但请记住,这是 Rust 编译器在早期(在编译时而不是运行时)指出潜在错误,并准确地告诉你问题所在。这样你就不必追踪为什么你的数据不是你想象的那样。
悬垂引用
在有指针的语言中,很容易错误地创建一个悬垂指针——一个引用内存中可能已经分配给其他人的位置的指针——通过释放一些内存而保留指向该内存的指针。相比之下,在 Rust 中,编译器保证引用永远不会是悬垂引用:如果你有一个对某些数据的引用,编译器将确保数据不会在引用之前离开作用域。
让我们尝试创建一个悬垂引用,看看 Rust 如何通过编译时错误来防止它们:
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
以下是错误信息:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0106]: missing lifetime specifier
--> src/main.rs:5:16
|
5 | fn dangle() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
5 | fn dangle() -> &'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
5 - fn dangle() -> &String {
5 + fn dangle() -> String {
|
error[E0515]: cannot return reference to local variable `s`
--> src/main.rs:8:5
|
8 | &s
| ^^ returns a reference to data owned by the current function
Some errors have detailed explanations: E0106, E0515.
For more information about an error, try `rustc --explain E0106`.
error: could not compile `ownership` (bin "ownership") due to 2 previous errors
这个错误信息提到了我们尚未涉及的一个特性:生命周期。我们将在第 10 章详细讨论生命周期。但是,如果你忽略关于生命周期的部分,消息确实包含了为什么这段代码有问题的关键:
此函数的返回类型包含一个借用值,但没有值可供借用
让我们仔细看看 dangle
代码的每个阶段发生了什么:
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String { // dangle returns a reference to a String
let s = String::from("hello"); // s is a new String
&s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped, so its memory goes away.
// Danger!
因为 s
是在 dangle
内部创建的,当 dangle
的代码执行完毕时,s
将被释放。但我们试图返回一个对它的引用。这意味着这个引用将指向一个无效的 String
。这不行!Rust 不会让我们这样做。
这里的解决方案是直接返回 String
:
fn main() { let string = no_dangle(); } fn no_dangle() -> String { let s = String::from("hello"); s }
这样就不会有任何问题。所有权被移出,没有任何东西被释放。
引用规则
让我们回顾一下我们讨论过的引用规则:
- 在任意给定时间,你可以要么拥有一个可变引用,要么拥有任意数量的不可变引用。
- 引用必须始终有效。
接下来,我们将看看另一种引用:切片。