
Lifetimes
Lifetime annotations, elision rules, 'static lifetime, struct lifetimes, lifetime bounds
1What is the main purpose of lifetimes in Rust?
What is the main purpose of lifetimes in Rust?
Câu trả lời
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.
2What syntax is used to annotate a lifetime on a reference?
What syntax is used to annotate a lifetime on a reference?
Câu trả lời
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.
3What does the 'static lifetime mean in Rust?
What does the 'static lifetime mean in Rust?
Câu trả lời
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.
How many lifetime elision rules does the Rust compiler automatically apply?
Why doesn't a function fn longest(x: &str, y: &str) -> &str compile?
+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
Iterators & Closures
Smart Pointers
Concurrency Basics
async/await
Testing
Cargo & Ecosystem
Pattern Matching
Macros
Serde & Serialization
Unsafe Rust
Advanced Traits
Advanced Lifetimes
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í