Rust

Lifetimes

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

20 domande da colloquioยท
Mid-Level
1

What is the main purpose of lifetimes in Rust?

Risposta

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?

Risposta

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?

Risposta

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 domande da colloquio

Padroneggia Rust per il tuo prossimo colloquio

Accedi a tutte le domande, flashcards, test tecnici, esercizi di code review e simulatori di colloquio.

Inizia gratis