Lifetimes em structs
Campos emprestados
Lifetimes em structs é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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
implheader - Prefer owning unless borrowing avoids meaningful copies
Perguntas Frequentes
A aula “Lifetimes em structs” é grátis?
Sim — o texto completo de “Lifetimes em structs” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.
O que vou aprender em “Lifetimes em structs”?
Campos emprestados Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Learn Rust Coding?
Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Lifetimes em structs”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Learn Rust Coding?
Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Por que usar lifetimes
- Anotações de lifetime
- Lifetimes em structs
- Regras de omissão