Rust

Lifetimes

Lifetime annotations, elision rules, 'static lifetime, struct lifetimes, lifetime bounds

20 preguntas de entrevista·
Mid-Level
1

What is the main purpose of lifetimes in Rust?

Respuesta

Lifetimes allow the compiler to verify that all references are valid for their entire usage. They ensure that a reference never outlives the data it refers to, preventing dangling references. The borrow checker uses lifetimes to validate memory safety at compile time, with no runtime overhead.

2

What syntax is used to annotate a lifetime on a reference?

Respuesta

Lifetimes are annotated with an apostrophe followed by a name, typically a lowercase letter like 'a. The syntax &'a T means a reference to T with lifetime 'a. By convention, 'a, 'b, 'c are used for generic lifetimes, but any valid identifier can be used after the apostrophe.

3

What does the 'static lifetime mean in Rust?

Respuesta

The 'static lifetime indicates that a reference can live for the entire duration of the program. String literals like "hello" automatically have the 'static lifetime because they are embedded in the binary. Global constants and values created with Box::leak also have this lifetime. Note: 'static doesn't mean the value existed from program start, but that it can live until the end.

4

How many lifetime elision rules does the Rust compiler automatically apply?

5

Why doesn't a function fn longest(x: &str, y: &str) -> &str compile?

+17 preguntas de entrevista

Domina Rust para tu próxima entrevista

Accede a todas las preguntas, flashcards, tests técnicos, ejercicios de code review y simuladores de entrevista.

Empieza gratis