所有権と借用

Rust Lifetimes Explained

Tell the compiler how long a returned reference stays valid with 'a.

  • 中級
  • 約3分で読めます
  • 実行できるサンプル 1 件
学べること
  • What a lifetime is
  • Annotating with 'a
  • Lifetimes in structs
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str
  1. 1a: &'a strinput
  2. 2b: &'a strinput
  3. 3-> &'a strvalid as long as both inputs

References must not outlive their data

A lifetime describes how long a reference is valid. Most of the time the compiler works it out. When a function returns a reference that could come from more than one parameter, you name the lifetime with 'a.

The signature of longest says that the result lives as long as both inputs do. subtitle is a string literal, which lives for the whole program, so result is still valid after the inner block. A struct that stores a reference needs a lifetime too.

重要なポイント

  1. Most lifetimes are worked out by the compiler.
  2. 'a links the result to the inputs.
  3. A struct that stores a reference needs a lifetime.

実行できる Rust のサンプル

Rust
コードを実行 →
main.rs
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() {
        a
    } else {
        b
    }
}

struct Highlight<'a> {
    text: &'a str,
}

fn main() {
    let title = String::from("The Rust Book");
    let result;
    {
        let subtitle = "2021 edition";
        result = longest(&title, subtitle);
    }
    println!("longest: {result}");

    let highlight = Highlight { text: &title[4..8] };
    println!("highlight: {}", highlight.text);
}
この例の実行ボタンを作成 実行結果
longest: The Rust Book
highlight: Rust

練習

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

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

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

チャレンジで練習する

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

すべてのチャレンジ