0Pricing
Learn Rust Coding · Lektion

Lifetimes in Structs

Geliehene Felder

Lifetimes in Structs ist eine kostenlose Learn Rust Coding-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Learn Rust Coding-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

Structs Can Borrow

Most structs own their data. But a struct can also hold a reference to data it does not own. When it does, the struct needs a lifetime parameter.

This guarantees the struct never outlives the borrowed data.

Declaring a Lifetime on a Struct

Add the lifetime in angle brackets after the struct name, then use it on the reference field. This says the struct cannot outlive that reference.

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

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first = novel.split('.').next().unwrap();
    let e = Excerpt { text: first };
    println!("{}", e.text);
}

The Constraint It Adds

The annotation means an instance of Excerpt is valid only while the string it borrows is alive. The compiler enforces this everywhere the struct is used.

Methods on Borrowing Structs

Methods on such a struct also carry the lifetime in the impl header. Often you can omit lifetimes in the method body thanks to elision (covered next lesson).

struct Excerpt<'a> { text: &'a str }

impl<'a> Excerpt<'a> {
    fn announce(&self) -> &str {
        println!("Attention!");
        self.text
    }
}

fn main() {
    let s = String::from("hello world");
    let e = Excerpt { text: &s };
    println!("{}", e.announce());
}

Why Not Just Own the Data?

Owning (using String) is simpler and usually preferred. Borrowing avoids copying large data and is useful for parsers and views that look into existing buffers.

Reach for lifetimes in structs only when borrowing pays off.

A Parser View Example

A struct that holds slices into a source string is a classic use. It reads the original buffer without copying.

struct Token<'a> {
    word: &'a str,
}

fn main() {
    let line = String::from("let x = 5");
    let tokens: Vec<Token> = line.split_whitespace().map(|w| Token { word: w }).collect();
    for t in &tokens {
        println!("token: {}", t.word);
    }
}

Multiple Reference Fields

A struct may hold several references. They can share one lifetime or use distinct ones, depending on how their validity relates.

struct Pair<'a> {
    left: &'a str,
    right: &'a str,
}

fn main() {
    let a = String::from("foo");
    let b = String::from("bar");
    let p = Pair { left: &a, right: &b };
    println!("{} {}", p.left, p.right);
}

The Dangling Struct Error

If the borrowed data is dropped while the struct still exists, the compiler rejects it. The lifetime parameter is what makes this check possible.

Returning Borrowing Structs

A function building such a struct ties the struct's lifetime to its input. The struct cannot outlive the data passed in.

struct Wrap<'a> { inner: &'a str }

fn wrap<'a>(s: &'a str) -> Wrap<'a> {
    Wrap { inner: s }
}

fn main() {
    let text = String::from("wrapped");
    let w = wrap(&text);
    println!("{}", w.inner);
}

Owned vs Borrowed Trade-off

Quick guide:

  • Need to keep data around independently? Own it (String, Vec).
  • Short-lived view into existing data? Borrow it with a lifetime.

Mental Model

A struct with 'a is like a sticky note attached to someone else's notebook: it is only meaningful while that notebook still exists. Rust makes sure you never read a note on a notebook that is gone.

Quick Check

Test your understanding of lifetimes in structs.

Recap

You learned lifetimes in structs:

  • A struct holding a reference needs a lifetime parameter
  • The lifetime ties the struct's validity to the borrowed data
  • Methods carry the lifetime in the impl header
  • Prefer owning unless borrowing avoids meaningful copies

Häufig gestellte Fragen

Ist die Lektion „Lifetimes in Structs“ kostenlos?

Ja — der vollständige Text von „Lifetimes in Structs“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Learn Rust Coding-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Lifetimes in Structs“?

Geliehene Felder Du übst Learn Rust Coding mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Learn Rust Coding zu starten?

Keine Vorkenntnisse erforderlich. Learn Rust Coding auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.

Wie lange dauert die Lektion „Lifetimes in Structs“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Learn Rust Coding-Lektion Code schreiben und ausführen?

Ja. Jede Learn Rust Coding-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Warum Lifetimes?
  2. Lifetime-Annotationen
  3. Lifetimes in Structs
  4. Elisionsregeln
← Zurück zu Learn Rust Coding