Ownership và borrowing

Rust References and Borrowing

Let a function use a value without taking it: & to read, &mut to change.

  • Trung cấp
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • & and &mut
  • Borrowing in function calls
  • Many readers or one writer
Borrow → what it allows
length(&message)read only
add_exclamation(&mut message)can change it
let first = &messagemany readers are fine

Use a value without owning it

A reference lets code use a value without owning it. This is called borrowing. &value borrows for reading and &mut value borrows for changing.

length only reads the text, so it takes &str and message can still be used afterwards. add_exclamation needs &mut String to change it. Rust allows many readers at once or one writer, but never both, which rules out data races at compile time.

Những điểm quan trọng

  1. &value borrows for reading.
  2. &mut value borrows for changing.
  3. Many readers or one writer, never both.

Ví dụ Rust chạy được

Rust
Chạy code →
main.rs
fn length(text: &str) -> usize {
    text.len()
}

fn add_exclamation(text: &mut String) {
    text.push('!');
}

fn main() {
    let mut message = String::from("Borrow me");

    let size = length(&message); // immutable borrow
    println!("{message} has {size} bytes");

    add_exclamation(&mut message); // mutable borrow
    println!("{message}");

    let first = &message;
    let second = &message; // many readers are fine
    println!("{first} {second}");
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
Borrow me has 9 bytes
Borrow me!
Borrow me! Borrow me!

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Slices →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách