0Pricing
Learn Rust Coding · Lección

Lifetimes en structs

Campos prestados

Lifetimes en structs es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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

Preguntas frecuentes

¿La lección «Lifetimes en structs» es gratis?

Sí — el texto completo de «Lifetimes en structs» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 4 lecciones en total.

¿Qué aprenderé en «Lifetimes en structs»?

Campos prestados Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn Rust Coding?

No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Lifetimes en structs»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?

Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Por qué existen los lifetimes
  2. Anotaciones de lifetime
  3. Lifetimes en structs
  4. Reglas de elisión
← Volver a Learn Rust Coding