0Pricing
Learn Rust Coding · Урок

Времена жизни в структурах

Заимствованные поля

«Времена жизни в структурах» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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

Часто задаваемые вопросы

Урок «Времена жизни в структурах» бесплатный?

Да — полный текст урока «Времена жизни в структурах» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.

Чему я научусь в уроке «Времена жизни в структурах»?

Заимствованные поля Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Learn Rust Coding?

Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Времена жизни в структурах»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Learn Rust Coding?

Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Зачем нужны времена жизни
  2. Аннотации времён жизни
  3. Времена жизни в структурах
  4. Правила вывода времён жизни
← Назад к Learn Rust Coding