Rust

Advanced Lifetimes

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

20 면접 질문·
Senior
1

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

답변

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))?

답변

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?

답변

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 면접 질문

다음 면접을 위해 Rust을 마스터하세요

모든 질문, flashcards, 기술 테스트, 코드 리뷰 연습, 면접 시뮬레이터에 접근하세요.

무료로 시작하기