Аннотации времён жизни
Именование времён жизни
«Аннотации времён жизни» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Naming a Lifetime
A lifetime annotation is a name starting with an apostrophe, like 'a. It does not change how long anything lives; it describes relationships between the lifetimes of references.
Where Annotations Go
You declare lifetime parameters in angle brackets after the function name, then use them on the reference types, just like generic type parameters.
Syntax: fn name<'a>(x: &'a T) -> &'a T.
The Classic longest Function
A function returning one of two references needs an annotation. 'a says the result lives as long as the shorter of the two inputs.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let a = String::from("long string");
let b = String::from("short");
println!("{}", longest(&a, &b));
}What 'a Means Here
The annotation tells the compiler: the returned reference is valid only while both inputs are valid. The compiler then checks every call site against this contract.
Why It Is Needed
Without the annotation, the compiler cannot know whether the return borrows from x or y. The lifetime name links them so the borrow checker can reason about the result.
Different Lifetimes
When references are unrelated, give them different lifetime names. Here only x is returned, so only its lifetime matters for the result.
fn first<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x
}
fn main() {
let a = String::from("keep me");
let b = String::from("ignore");
println!("{}", first(&a, &b));
}Lifetimes Do Not Extend Life
Annotations never make data live longer. They only state constraints the compiler must verify. If a value dies too soon, the code will not compile regardless of annotations.
A Valid Call
As long as both inputs outlive the use of the result, the call is accepted. Here both strings live through the print, so all is well.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let a = String::from("abcdef");
let result;
{
let b = String::from("xy");
result = longest(&a, &b);
println!("chosen: {}", result);
}
}Lifetimes With Generics
Lifetime and type parameters can appear together. Lifetimes are listed first inside the angle brackets.
use std::fmt::Display;
fn announce<'a, T: Display>(text: &'a str, value: T) -> &'a str {
println!("value is {}", value);
text
}
fn main() {
let msg = String::from("hello");
println!("{}", announce(&msg, 42));
}The 'static Lifetime
'static is a special lifetime meaning the reference can live for the entire program. String literals have it because they are baked into the binary.
fn motto() -> &'static str {
"fearless concurrency"
}
fn main() {
println!("{}", motto());
}Reading Annotations
Read &'a str as a string reference valid for lifetime 'a. When two parameters share 'a, the compiler ties their lifetimes to whichever is shorter at each call.
Quick Check
Test your understanding of lifetime annotations.
Recap
You learned to name lifetimes:
- Lifetimes use names like
'a, declared in angle brackets - Shared names express that references relate (e.g. result tied to inputs)
- Annotations describe, never extend, lifetimes
'staticmeans valid for the whole program
Часто задаваемые вопросы
Урок «Аннотации времён жизни» бесплатный?
Да — полный текст урока «Аннотации времён жизни» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.
Чему я научусь в уроке «Аннотации времён жизни»?
Именование времён жизни Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Learn Rust Coding?
Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Аннотации времён жизни»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Learn Rust Coding?
Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Зачем нужны времена жизни
- Аннотации времён жизни
- Времена жизни в структурах
- Правила вывода времён жизни