
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?
คำตอบ
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?
คำตอบ
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?
คำตอบ
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 คำถามสัมภาษณ์
หัวข้อสัมภาษณ์ Rust อื่นๆ
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
เชี่ยวชาญ Rust สำหรับการสัมภาษณ์ครั้งถัดไป
เข้าถึงคำถามทั้งหมด flashcards แบบทดสอบเทคนิค แบบฝึกหัด code review และตัวจำลองสัมภาษณ์
เริ่มใช้ฟรี