Rust interview Questions and Answers: Part-2

Rust interview Questions and Answers: Part-2

ยท

4 min read

  1. What happens to owned data upon the completion of a Rust function?

    In Rust, when a function takes ownership of data, that data is dropped (deleted) at the end of the function. This occurs because all owned data is dropped at the end of the scope, and a function's end marks the end of its scope.

  2. Explain the purpose of #[derive(Debug)] in Rust.

    The #[derive(Debug)] attribute in Rust enables a struct or enum to be printed using the debug formatting token {:?} within the println! and format! macros.

  3. Distinguish between .unwrap() and .expect() in Rust.

    Both .unwrap() and .expect() will trigger a panic upon execution. However, .unwrap() triggers a thread panic and displays the line number containing the call, while .expect() triggers a panic with a custom message before displaying the line number.

  4. Why is the return keyword optional in Rust?

    Provide examples. In Rust, the return keyword is optional due to its expression-based nature. Expressions are evaluated, and their results propagate outward, unlike statements in other languages. If there's no need to return early from a function, omitting the return keyword is appropriate. For instance:

fn one() -> u32 {
    1
}

fn two() -> u32 {
    return 2;
}
  1. Offer an example of a match expression in Rust.

    The following match expression in Rust demonstrates matching an Option, printing data if Some and printing a message if None:

let foo = Some(1);
match foo {
    Some(n) => println!("number is {n}"),
    None => println!("there is no number"),
}
  1. Can the result of a Rust match expression be assigned to a variable binding? Yes, since match is an expression in Rust, assigning its result is possible:

let t = true;
let one = match t {
    true => 1,
    false => 0,
};
  1. What happens when you add a new variant to a Rust enum without altering other code?

    Adding a new variant to a Rust enum without updating other code may lead to compiler errors elsewhere in the program, especially if match expressions aren't updated to handle the new variant.

  2. Which Rust keyword iterates through a collection?

    The "for" keyword iterates through a collection in Rust:

let nums = vec![1, 2, 3];
for n in nums {
    println!("{n}")
}
  1. How do you print information to the terminal in Rust?

    Information in Rust is printed to the terminal using the println! macro:

println!("hello world");

Additionally, for debugging purposes, the dbg! macro is available:

let life = 42;
dbg!(life);
  1. Define a Rust Vec and its usage scenarios.

    A Vec in Rust is a linear collection of elements similar to a dynamic array. It's used for storing elements in a defined order and iterating over them when needed.

  2. Can multiple variables be created in a single line of Rust code?

    Yes, by employing a destructuring operation, multiple variables can be created in a single line:

let (a, b) = (1, 2);

However, creating multiple uninitialized variables in a single line isn't possible.

  1. What is a Rust trait?

    In Rust, traits declare the existence of certain behavior, with specific implementations provided by data that implements the trait. Traits serve as a way to define interfaces where the interface dictates what can happen, while the implementation determines how it happens.

  2. Explain generics in Rust.

    Generics in Rust enable the creation of structures, enums, or functions without specifying the exact type of data they will operate on. Traits act as generic constraints, ensuring that the data used with generics adhere to the required traits.

  3. How do you borrow data within a Rust structure?

    To borrow data within a Rust structure, lifetime annotations are used. These annotations indicate that the structure is borrowing data from another part of the program. For example:

#[derive(Debug)]
struct Name<'a> {
    name: &'a str,
}

let name = String::from("Bob");
let n = Name { name: &name };
  1. Is it possible to continue an outer loop from an inner loop in Rust?

    Yes, using loop labels enables continuing an outer loop from an inner loop in Rust:

let mut a = 0;
'outer: loop {
    a += 1;

    let mut b = 0;
    loop {
        if b == 3 {
            continue 'outer;
        }
        b += 1;
    }
}

Using loop labels with the break keyword allows an inner loop to exit both the inner and outer loops.

More such articles:

https://medium.com/techwasti

https://www.youtube.com/@maheshwarligade

https://techwasti.com/series/spring-boot-tutorials

https://techwasti.com/series/go-language

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

ย