Rust

Advanced Lifetimes

Higher-ranked trait bounds (HRTB), lifetime subtyping, variance (covariant, contravariant, invariant), 'static vs 'a, NLL

20 interview questionsยท
Senior
1

What is a Higher-Ranked Trait Bound (HRTB) in Rust?

Answer

A Higher-Ranked Trait Bound (HRTB) allows specifying that a function or trait must work for all possible lifetimes, not just a specific one. The for<'a> syntax indicates that the bound must be satisfied for any lifetime 'a chosen by the caller. This feature is essential for closures and callbacks that need to accept references with varying lifetimes.

2

What is the difference between fn foo<'a>(f: impl Fn(&'a str)) and fn foo(f: impl for<'a> Fn(&'a str))?

Answer

With fn foo<'a>, the lifetime 'a is fixed by the caller at call time and remains the same throughout execution. With for<'a>, the closure must work for any lifetime, allowing it to be called multiple times with references of different lifetimes. This distinction is crucial for APIs that call a closure multiple times with different temporary references.

3

What is lifetime subtyping in Rust and what does 'a: 'b mean?

Answer

Lifetime subtyping establishes a subtyping relationship between lifetimes. The notation 'a: 'b means 'a lives at least as long as 'b, so 'a is a subtype of 'b. A reference with a longer lifetime can be used where a shorter lifetime is expected. This relationship is covariant for immutable references, allowing a reference with a longer lifetime to be passed where a shorter one would suffice.

4

What is variance in Rust and how does it affect generic types?

5

Why is &mut T invariant with respect to T while &T is covariant?

+17 interview questions

Master Rust for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free