소유권과 빌림

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

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Smart Pointers: Box and Rc →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지