共享引用

A reference provides a way to access another value without taking ownership of the value, and is also called “borrowing”. Shared references are read-only, and the referenced data cannot change.

fn main() {
    let a = 'A';
    let b = 'B';

    let mut r: &char = &a;
    dbg!(r);

    r = &b;
    dbg!(r);
}

对类型 T 的共享引用表示为 &T。可以使用 & 运算符创建引用值。* 运算符会 “解引用”某个引用,并得到该引用值。

This slide should take about 7 minutes.
  • References can never be null in Rust, so null checking is not necessary.

  • 引用被称为 “借用”了其所引用的值,这对于不熟悉指针的学生来说是一个很好的模型:代码可以通过引用来访问值,但原始变量仍然保有对该值的 “所有权”。本课程会在第 3 天详细介绍所有权。

  • 引用是以指针的形式实现的,其关键优势在于它们可以比其所指的内容小得多。熟悉 C 或 C++ 的学生会将引用视为指针。本课程的后续部分将介绍 Rust 如何防止因使用原始指针而导致的内存安全 bug。

  • Explicit referencing with & is usually required. However, Rust performs automatic referencing and dereferencing when invoking methods.

  • Rust will auto-dereference in some cases, in particular when invoking methods (try r.is_ascii()). There is no need for an -> operator like in C++.

  • 在本例中,r 是可变的,因此可以为其重新赋值 (r = &b)。请注意,这会重新绑定 r,使其引用其他内容。这与 C++ 不同,在 C++ 中为引用赋值会更改引用的值。

  • 共享引用不允许修改其所引用的值,即使该值是可变的。请尝试 *r = 'X'

  • Rust is tracking the lifetimes of all references to ensure they live long enough. Dangling references cannot occur in safe Rust.

  • We will talk more about borrowing and preventing dangling references when we get to ownership.