Rust 引用和借用

Rust 中的**引用**允许我们指向一个资源(值)而不拥有它。这意味着资源的原始所有者保持不变。

在传递我们不想改变所有权的参数给函数时,引用非常有用。创建引用在 Rust 中被称为**借用**。


理解 Rust 中的引用

让我们通过一个例子来学习 Rust 中的引用。

fn main() {
    let str = String::from("Hello, World!");
    
// Call function with reference String value let len = calculate_length(&str);
println!("The length of '{}' is {}.", str, len); } // Function to calculate length of a string // It takes a reference of a String as an argument
fn calculate_length(s: &String) -> usize { s.len() }

输出

The length of 'Hello, World!' is 13.

在上面的示例中,我们定义了一个名为 calculate_length() 的函数,它接受一个 &String 类型的参数。

这里重要的是 s 是对 String 的引用,它不拥有 String 的实际值。

fn calculate_length(s: &String) -> usize { // s is a reference to a String
    s.len()
}

s 超出作用域时,在函数结束时,它不会被丢弃,因为它不拥有它所引用的内容。

函数调用如下

let str = String::from("Hello, World!");

let len = calculate_length(&str);

在调用函数时,&str 语法允许我们创建一个**引用**,它引用 str 的值但不拥有它。

创建引用的行为被称为**借用**。借用就是我们借用某物,用完之后,将其归还。它不会使我们成为数据的拥有者。

注意: Ampersand (&) 代表引用,它们允许我们引用某个值而不拥有它。


修改 Rust 中的引用

默认情况下,引用始终是不可变的。但是,我们可以使用 &mut 关键字来使引用可变。

例如,

fn main() {
    let mut str = String::from("Hello");
    
    // before modifying the string
    println!("Before: str = {}", str);

// pass a mutable string when calling the function change(&mut str);
// after modifying the string println!("After: str = {}", str); }
fn change(s: &mut String) { // push a string to the mutable reference variable s.push_str(", World!"); }

输出

Before: str = Hello
After: str = Hello, World!

在这里,我们将变量 str 设置为可变。然后我们使用 &mut str 创建一个可变引用,并使用可变引用 s: &mut String 调用 change() 函数。

这允许 change() 函数修改它借用的值。在 change() 函数中,我们使用 s.push_str(", World!") 向引用字符串添加一个字符串。

注意: 如果您有一个值的可变引用,那么您不能拥有该值的任何其他引用。

fn main() {
    let mut str = String::from("hello");

    // mutable reference 1
    let ref1 = &mut str;

    // mutable reference 2
    let ref2 = &mut str;

    println!("{}, {}", ref1, ref2);
}

输出

error[E0499]: cannot borrow `str` as mutable more than once at a time
  --> src/main.rs:8:16
   |
5  |     let ref1 = &mut str;
   |                -------- first mutable borrow occurs here
...
8  |     let ref2 = &mut str;
   |                ^^^^^^^^ second mutable borrow occurs here
9  |
10 |     println!("{}, {}", ref1, ref2);
   |                        ---- first borrow later used here

引用的规则

在任何给定时间,Rust 主要遵循这些引用规则:

  1. 在任何给定时间,您只能有一个可变引用,或者任意数量的不可变引用。
  2. 引用必须始终有效。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战