Any2Quiz
Computer Science / Languages / Rust

Lifetimes Quiz - Languages Rust

Free practice quiz: Lifetimes (Languages Rust). 40 multiple-choice questions with answers and explanations. Play online, no sign-up needed.

Play all 40 questions free

Sample questions

  1. In Rust, what is the primary purpose of lifetimes?

    1. To ensure that references do not outlive the data they point to.
    2. To manage memory allocation and deallocation automatically.
    3. To enforce type safety at compile time.
    4. To allow for concurrent data access without data races.
    Show answer

    Answer: A. To ensure that references do not outlive the data they point to.

    Lifetimes are a compile-time mechanism in Rust that prevents dangling references. They ensure that a reference is always valid and points to valid data. This is crucial for memory safety.

  2. Which of the following is NOT a valid lifetime elision rule in Rust?

    1. If there is exactly one input lifetime parameter, that lifetime is assigned to the return value.
    2. If there are multiple input lifetime parameters, but one of them is `&self` or `&mut self`, the lifetime of `self` is assigned to the return value.
    3. If there are multiple input lifetime parameters and the output lifetime cannot be determined, the output lifetime is always `'static`.
    4. If a reference parameter is a field in a struct, its lifetime is tied to the struct's lifetime.
    Show answer

    Answer: C. If there are multiple input lifetime parameters and the output lifetime cannot be determined, the output lifetime is always `'static`.

    Rust's lifetime elision rules are designed to avoid ambiguity. The third option is incorrect; if the output lifetime cannot be determined from the inputs (especially with multiple inputs without a clear relationship to the output), the compiler will require explicit lifetime annotations, rather than defaulting to `'static` which might be incorrect and unsafe.

  3. What does the following code snippet attempt to do, and what lifetime issue might arise?

    1. `let mut vec = vec![1, 2]; let r1 = &vec; let r2 = &vec[0]; vec.push(3);` The issue is that `r1` might become invalid if `vec.push(3)` causes reallocation, invalidating `r2`.
    2. `let mut vec = vec![1, 2]; let r1 = &vec; let r2 = &vec[0]; vec.push(3);` The issue is that `r2` might become invalid if `vec.push(3)` causes reallocation, invalidating `r1`.
    3. `let mut vec = vec![1, 2]; let r1 = &vec; let r2 = &vec[0]; vec.push(3);` No lifetime issue arises as `vec` is mutable.
    4. `let mut vec = vec![1, 2]; let r1 = &vec; let r2 = &vec[0]; vec.push(3);` The issue is a type mismatch between `r1` and `r2`.
    Show answer

    Answer: B. `let mut vec = vec![1, 2]; let r1 = &vec; let r2 = &vec[0]; vec.push(3);` The issue is that `r2` might become invalid if `vec.push(3)` causes reallocation, invalidating `r1`.

    When you `push` into a `Vec` that might need to reallocate its internal buffer, all existing references to elements within that `Vec` (like `r2`) can become invalidated. Although `r1` is a reference to the `Vec` itself, the potential reallocation is the core issue that can break `r2`. Rust's borrow checker will prevent this code from compiling because the mutable borrow via `vec.push(3)` conflicts with the immutable borrow `r1` (and by extension, `r2`), but the underlying concern is the invalidation of `r2` if `push` reallocates.

  4. Consider a function that takes a reference to a string slice and returns a reference to a character within that slice. What is the most appropriate lifetime annotation?

    1. `fn get_first_char<'a>(s: &'a str) -> Option<&'a u8>`
    2. `fn get_first_char(s: &str) -> Option<&u8>`
    3. `fn get_first_char<'a>(s: &'a str) -> Option<&'static u8>`
    4. `fn get_first_char<'a>(s: &'a str) -> Option<&'b u8>`
    Show answer

    Answer: A. `fn get_first_char<'a>(s: &'a str) -> Option<&'a u8>`

    The function receives a string slice with lifetime `'a`. It returns a reference to a byte within that string slice. Therefore, the returned reference's lifetime must be tied to the input reference's lifetime `'a`. Using `Option<&'a u8>` correctly expresses this.

  5. Can a struct definition itself have lifetime parameters?

    1. Yes, if the struct contains references, it must be parameterized by the lifetimes of those references.
    2. No, lifetimes are only for functions and methods.
    3. Yes, but only if the struct is `#[derive(Clone)]`.
    4. Yes, but only if the struct's fields are primitive types.
    Show answer

    Answer: A. Yes, if the struct contains references, it must be parameterized by the lifetimes of those references.

    Structs that hold references need to declare lifetime parameters to ensure memory safety. These parameters are bound to the lifetimes of the references within the struct, preventing the struct from outliving the data its references point to.

Take the full quiz

More quizzes

Browse all Rust quizzes