
Advanced Lifetimes
Higher-ranked trait bounds (HRTB), lifetime subtyping, variance (covariant, contravariant, invariant), 'static vs 'a, NLL
1What is a Higher-Ranked Trait Bound (HRTB) in Rust?
What is a Higher-Ranked Trait Bound (HRTB) in Rust?
Câu trả lời
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.
2What is the difference between fn foo<'a>(f: impl Fn(&'a str)) and fn foo(f: impl for<'a> Fn(&'a str))?
What is the difference between fn foo<'a>(f: impl Fn(&'a str)) and fn foo(f: impl for<'a> Fn(&'a str))?
Câu trả lời
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.
3What is lifetime subtyping in Rust and what does 'a: 'b mean?
What is lifetime subtyping in Rust and what does 'a: 'b mean?
Câu trả lời
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.
What is variance in Rust and how does it affect generic types?
Why is &mut T invariant with respect to T while &T is covariant?
+17 câu hỏi phỏng vấn
Các chủ đề phỏng vấn Rust khác
Rust Basics
Ownership & Borrowing
Structs & Enums
Error Handling
Collections
Modules & Packages
Traits
Generics
Lifetimes
Iterators & Closures
Smart Pointers
Concurrency Basics
async/await
Testing
Cargo & Ecosystem
Pattern Matching
Macros
Serde & Serialization
Unsafe Rust
Advanced Traits
Type System
Tokio & Async I/O
Performance Optimization
Memory Management
Web Frameworks
Database Integration
Rust Design Patterns
Nắm vững Rust cho lần phỏng vấn tiếp theo
Truy cập tất cả câu hỏi, flashcards, bài kiểm tra kỹ thuật, bài tập code review và mô phỏng phỏng vấn.
Bắt đầu miễn phí