Câu hỏi phỏng vấn Rust
Câu hỏi

What’s a closure in Rust?

Câu trả lời

A closure in Rust is an anonymous function that can capture variables from its surrounding environment. Unlike regular functions, closures can access and manipulate variables that are in scope at the time they are defined. This makes them particularly useful for scenarios where you need to pass around bits of functionality that can operate on data available in the current context.

Key Characteristics of Closures in Rust

  1. Anonymous Functions: Closures do not have a name and are defined using a syntax that involves vertical bars (|) to enclose parameters, followed by the function body. For example:

    rust Copy
    let add_one = |x| x + 1;
    println!("{}", add_one(5)); // prints 6
  2. Environment Capturing: Closures can capture variables from their surrounding scope. This can be done by reference, mutable reference, or by value, depending on how the closure is defined and used. Rust provides three traits to classify closures based on how they capture variables:

    • Fn: Captures variables by reference (&T).
    • FnMut: Captures variables by mutable reference (&mut T).
    • FnOnce: Captures variables by value (T).
  3. Syntax and Type Inference: The syntax for closures is more concise than for regular functions. Type annotations for parameters and return types are optional and can be inferred by the compiler. For example:

    rust Copy
    let add = |a: i32, b: i32| -> i32 { a + b };
    let result = add(2, 3); // result is 5
  4. Usage in Higher-Order Functions: Closures are often used as arguments to other functions, enabling flexible and reusable code patterns. For instance, the Iterator trait in Rust's standard library makes extensive use of closures.

  5. Move Keyword: The move keyword can be used to force a closure to take ownership of the variables it captures from the environment. This is particularly useful when passing closures to threads:

    rust Copy
    let x = vec![1, 2, 3];
    let closure = move || println!("{:?}", x);

Example of Different Closure Traits

  • Fn Closure:

    rust Copy
    let print = || println!("This is a Fn closure.");
    print(); // This is a Fn closure.
  • FnMut Closure:

    rust Copy
    let mut count = 0;
    let mut increment = || {
        count += 1;
        println!("count: {}...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

Why are Rust executables so huge? How would you optimise it?

middle

What is the difference between iter and into_iter in Rust?

middle

Explain what is Trait in Rust? What are some use cases when you need to implement one?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào