所有権と借用

Rust References and Borrowing

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

  • 中級
  • 約3分で読めます
  • 実行できるサンプル 1 件
学べること
  • & 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.

重要なポイント

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

実行できる Rust のサンプル

Rust
コードを実行 →
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}");
}
この例の実行ボタンを作成 実行結果
Borrow me has 9 bytes
Borrow me!
Borrow me! Borrow me!

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

次へ: Slices →

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ