0Pricing
Learn Rust Coding · Lektion

Warum Lifetimes?

Dangling References verhindern

Warum Lifetimes? ist eine kostenlose Learn Rust Coding-Lektion auf CoddyKit. Dies ist Lektion 1 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.

References Must Stay Valid

A reference borrows data it does not own. Rust must guarantee the data lives at least as long as the reference. Lifetimes are how the compiler tracks this.

Their job: prevent dangling references.

What Is a Dangling Reference?

A dangling reference points to memory that has been freed. In languages without checks, using one causes crashes or security bugs. Rust refuses to compile such code.

The Borrow Checker in Action

This code would create a reference to a value that goes out of scope. Rust rejects it at compile time. Lifetimes are the rule it uses to decide.

fn main() {
    let r;
    {
        let x = 5;
        r = &x;
        println!("inside: {}", r);
    }
    // using r here would be a dangling reference
    println!("done");
}

Scopes Define Lifetimes

A value's lifetime is the span where it is valid, usually its scope. A reference must not outlive the value it points to.

Here both x and the reference live in the same scope, so it is fine.

fn main() {
    let x = 5;
    let r = &x;
    println!("x is {}, r is {}", x, r);
}

Returning References

A function returning a reference must return one that stays valid for the caller. You cannot return a reference to a local variable, because it dies when the function ends.

Returning a Borrow of an Input

What you can do is return a reference that borrows from an input. The result is valid as long as that input is. This is exactly what lifetime annotations describe.

fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();
    for (i, &b) in bytes.iter().enumerate() {
        if b == b' ' {
            return &s[..i];
        }
    }
    s
}

fn main() {
    let sentence = String::from("hello world");
    println!("{}", first_word(&sentence));
}

Lifetimes Are Compile-Time Only

Lifetimes are purely a compile-time concept. They add no runtime cost and exist only to let the borrow checker verify memory safety.

Ownership and Lifetimes Together

Ownership decides who frees a value; lifetimes decide how long borrows of it may live. Together they let Rust guarantee safety without a garbage collector.

fn main() {
    let data = vec![1, 2, 3];
    let view = &data[0..2];
    println!("{:?}", view);
    // data still owns the vector; view just borrows part of it
    println!("{:?}", data);
}

Why Names Appear in Signatures

When a function takes multiple references, the compiler sometimes cannot tell how their lifetimes relate. You then add lifetime annotations to clarify the relationships.

The next lesson covers that syntax.

The Payoff

Because of lifetimes, an entire category of bugs — use-after-free, dangling pointers, iterator invalidation — simply cannot compile. You get C-like speed with memory safety.

Mental Model

Think of a lifetime as a label on the duration data is alive. A reference carries the constraint: I am valid only while my source is alive. The borrow checker enforces it.

Quick Check

Test your understanding of why lifetimes exist.

Recap

You learned why lifetimes exist:

  • References must not outlive the data they borrow
  • Lifetimes prevent dangling references at compile time
  • They are compile-time only, with no runtime cost
  • They work alongside ownership for memory safety without a GC

Häufig gestellte Fragen

Ist die Lektion „Warum Lifetimes?“ kostenlos?

Ja — der vollständige Text von „Warum Lifetimes?“ 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 „Warum Lifetimes?“?

Dangling References verhindern 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 1 von 4.

Wie lange dauert die Lektion „Warum Lifetimes?“?

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