
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?
Jawaban
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?
Jawaban
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?
Jawaban
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 pertanyaan wawancara
Topik wawancara Rust lainnya
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
Kuasai Rust untuk wawancara berikutnya
Akses semua pertanyaan, flashcards, tes teknis, latihan code review dan simulator wawancara.
Mulai gratis