Rust Interview MCQs

Rust Interview MCQs

Hey there! I’ve got a set of Rust Interview MCQs (50 questions) to help you ace your prep. Each comes with a clear answer and a straightforward explanation to make sure you get the concepts. Let’s dive in!


1. What’s the main purpose of Rust’s ownership model?

A. Manually managing memory allocation
B. Preventing memory leaks and ensuring safety without a garbage collector
C. Handling threads
D. Speeding up compilation

Answer: B
Explanation:
Rust’s ownership system tracks who owns what memory and cleans it up when it’s no longer needed, all without a garbage collector. It’s about safe and efficient memory management.


2. Which keyword defines a constant in Rust?

A. let
B. mut
C. const
D. static mut

Answer: C
Explanation
: Use const for compile-time constants. They’re immutable and need a type annotation, like const PI: f32 = 3.14;.


3. What does unwrap() do on a Result or Option?

A. Returns an error message
B. Gets the value or panics if it’s None or Err
C. Converts to a string
D. Ignores the value

Answer: B
Explanation
: unwrap() pulls out the value from Some or Ok, but if it’s None or Err, your program crashes with a panic. Use it carefully!


4. What’s the difference between String and &str?

A. String is fixed-size; &str is growable
B. String is heap-allocated and growable; &str is a borrowed string slice
C. String is immutable; &str is mutable
D. They’re identical

Answer: B
Explanation
: String is a mutable, owned string on the heap that can grow. &str is an immutable view into a string, often a slice of a String or a string literal.


5. Which trait lets a type be printed with {} in println!?

A. Debug
B. Display
C. Clone
D. ToString

Answer: B
Explanation
: The Display trait handles formatting for {} in println!. Debug is for {:?}, which is more for developer-friendly output.


6. What does the mut keyword do?

A. Declares a function
B. Makes a variable mutable
C. Imports a module
D. Enables a macro

Answer: B
Explanation
: Variables in Rust are immutable by default. Add mut (like let mut x = 5;) to allow changes.


7. What’s a crate in Rust?

A. A variable
B. A package of Rust code
C. A type of loop
D. A macro

Answer: B
Explanation
: A crate is Rust’s term for a library or executable project. It’s the unit of compilation.


8. What’s Cargo in Rust?

A. A testing framework
B. A linter
C. A package manager and build system
D. A debugger

Answer: C
Explanation
: Cargo is Rust’s go-to tool for managing dependencies, building projects, and running tests.


9. Which keyword defines a module?

A. mod
B. module
C. use
D. crate

Answer: A
Explanation
: Use mod to declare a module, like mod utils; for organizing code.


10. What’s the output of this code?

rust

fn main() {
    let x = 5;
    let y = x;
    println!("x = {}, y = {}", x, y);
}

A. Compilation error due to move
B. x = 5, y = 5
C. x = 5, y = undefined
D. Runtime panic

Answer: B
Explanation
: i32 is a Copy type, so y = x copies the value. Both x and y are valid and print 5.


11. Which trait allows a struct to be cloned?

A. Display
B. Copy
C. Clone
D. Debug

Answer: C
Explanation
: The Clone trait lets you make a deep copy of a value by calling .clone(). Copy is for simpler, automatic copies.


12. What’s the purpose of Result<T, E>?

A. Represents a list
B. Handles errors or success explicitly
C. Wraps boolean conditions
D. Creates dynamic types

Answer: B
Explanation
: Result is an enum with Ok(T) for success or Err(E) for errors, making error handling explicit and safe.


13. What are lifetimes ‘a used for?

A. Making functions async
B. Indicating thread scope
C. Ensuring references are valid
D. Denoting variable mutability

Answer: C
Explanation
: Lifetimes like ‘a tell the compiler how long references live, preventing dangling pointers.


14. What does Vec::new() return?

A. A reference to a vector
B. A vector with one empty item
C. An empty vector
D. A null pointer

Answer: C
Explanation
: Vec::new() gives you a fresh, empty vector ready to hold items.


15. What does the ? operator do?

A. Ignores errors
B. Panics on error
C. Propagates errors from Result
D. Forces a return of Option

Answer: C
Explanation
: The ? operator is a shortcut to pass an error up the call stack if a Result is Err, making error handling cleaner.


16. What’s the output of this code?

rust

fn main() {
    let s = String::from("Hello");
    let t = s;
    println!("{}", s);
}

A. Hello
B. Error: value moved
C. Runtime panic
D. s = None

Answer: B
Explanation
: Assigning s to t moves ownership of the String. Trying to use s afterward causes a compile-time error.


17. Which type is stack-allocated?

A. Box<T>
B. String
C. i32
D. Vec<T>

Answer: C
Explanation
: Simple types like i32 live on the stack. Box, String, and Vec involve heap memory.


18. What’s the purpose of #[derive(Debug)]?

A. Makes a trait global
B. Allows manual trait implementation
C. Automatically implements traits
D. Speeds up compilation

Answer: C
Explanation
: #[derive(Debug)] auto-implements the Debug trait so you can print a struct with {:?}.


19. What’s the output of this code?

rust

fn main() {
    let mut v = vec![1, 2, 3];
    v.push(4);
    println!("{:?}", v);
}

A. [1, 2, 3]
B. [4]
C. [1, 2, 3, 4]
D. Compilation error

Answer: C
Explanation
: push adds 4 to the mutable vector, so it prints [1, 2, 3, 4].


20. Which keyword defines an enum?

A. struct
B. enum
C. type
D. union

Answer: B
Explanation
: Use enum to create enumerations, like enum Color { Red, Blue }.


21. Which trait is auto-implemented for types with Display?

A. Clone
B. PartialEq
C. ToString
D. Drop

Answer: C
Explanation
: If a type implements Display, it gets ToString for free, letting you call .to_string().


22. What does std::cmp::PartialEq do?

A. Enables debugging
B. Allows comparison with ==
C. Handles memory cleanup
D. Enables hashing

Answer: B
Explanation
: PartialEq lets you use == and != to compare values.


23. What’s true about Rust’s error handling?

A. Uses exceptions like Java
B. All errors are panics
C. Uses Result and Option for recoverable errors
D. Ignores errors by default

Answer: C
Explanation
: Rust handles errors with Result for recoverable cases and Option for nullable values. Panics are for unrecoverable issues.


24. What’s the purpose of Box<T>?

A. Implements threading
B. Allocates on the stack
C. Allocates on the heap
D. Stores string literals

Answer: C
Explanation
: Box<T> puts a value on the heap, giving you a pointer to it on the stack.


25. Which function matches enum variants?

A. unwrap()
B. expect()
C. match
D. as_ref()

Answer: C
Explanation
: match lets you handle each variant of an enum, like Ok or Err in Result.


26. What happens when you call .clone() on a vector?

A. Copies a reference
B. Shallow-copies heap elements
C. Deep-copies the vector and its contents
D. Causes a compilation error

Answer: C
Explanation
: .clone() makes a full copy of the vector and all its elements, assuming they implement Clone.


27. What’s the benefit of Rust’s type inference?

A. Enables runtime type casting
B. Reduces compile time
C. Avoids type annotations when obvious
D. Makes types dynamic

Answer: C
Explanation
: Rust infers types where possible, so you don’t always need to write them out, keeping code clean.


28. Which macro writes unit tests?

A. #test
B. unit!
C. #[test]
D. @test

Answer: C
Explanation
: Mark a function with #[test] to make it a unit test, run with cargo test.


29. Which keyword imports modules or traits?

A. mod
B. use
C. impl
D. include

Answer: B
Explanation
: use brings modules, traits, or items into scope, like use std::fs::File;.


30. What does the impl keyword do?

A. Imports a module
B. Implements methods or traits for a type
C. Declares a variable
D. Creates an object

Answer: B
Explanation
: Use impl to define methods or implement traits for a type, like impl MyStruct { … }.


31. Which type represents a nullable value?

A. Err
B. Result
C. Option
D. Maybe

Answer: C
Explanation
: Option is either Some(T) or None, perfect for values that might not exist.


32. What’s the Drop trait for?

A. Manually freeing memory
B. Cleaning up when a value goes out of scope
C. Cloning values
D. Comparing values

Answer: B
Explanation
: Drop runs custom cleanup code (like closing files) when a value is dropped.


33. How do you create a thread in Rust?

A. std::spawn()
B. thread::start()
C. thread::spawn()
D. Thread::new()

Answer: C
Explanation
: std::thread::spawn starts a new thread with a closure, like thread::spawn(|| { … }).


34. How do you borrow a variable immutably?

A. let a = mut &x;
B. let a = &x;
C. let a = x;
D. let a = &&mut x;

Answer: B
Explanation
: &x creates an immutable borrow, letting you read x without changing it.


35. What happens if you borrow mutably and immutably at the same time?

A. It’s allowed
B. Program crashes
C. Runtime panic
D. Compiler error

Answer: D
Explanation
: Rust’s borrow checker blocks this to prevent data races. You can have one mutable borrow or multiple immutable ones, not both.


36. What does ref do in a match pattern?

A. Matches a reference
B. Forces a move
C. Converts to a reference
D. Assigns a mutable reference

Answer: A
Explanation
: ref in match lets you borrow a value instead of moving it, keeping the original usable.


37. What’s a trait in Rust?

A. A macro
B. A type alias
C. A collection
D. Shared behavior (like an interface)

Answer: D
Explanation
: Traits define behaviors types can implement, like interfaces in other languages.


38. What’s the difference between Copy and Clone?

A. Copy is deep copy; Clone is shallow
B. Copy is for primitives; Clone is for heap types
C. Copy is implicit; Clone needs a method call
D. No difference

Answer: C
Explanation
: Copy happens automatically (like for i32), while Clone requires calling .clone() for explicit copying.


39. What does the as keyword do?

A. Declares a struct
B. Converts one type to another
C. Defines a trait
D. Defines a closure

Answer: B
Explanation
: as casts types, like let x = 5_i32 as f32;.


40. What’s the output of this code?

rust

fn main() {
    let x = 10;
    let y = &x;
    println!("{}", y);
}

A. Compilation error
B. 10
C. Memory address
D. None

Answer: B
Explanation
: y is a reference to x, and println! dereferences it to print 10.


41. Which keyword makes a variable mutable?

A. mut
B. var
C. let mut
D. change

Answer: C
Explanation
: let mut declares a mutable variable. mut alone isn’t enough.


42. What’s the :: operator for?

A. Method invocation
B. Importing crates
C. Namespace resolution or associated function access
D. Dereferencing pointers

Answer: C
Explanation
: :: accesses items in modules or calls associated functions, like Vec::new().


43. Which keyword implements a trait for a type?

A. trait
B. use
C. mod
D. impl

Answer: D
Explanation
: impl is used to implement traits or methods, like impl MyTrait for MyType { … }.


44. What’s a closure in Rust?

A. A thread
B. A struct
C. An anonymous function capturing its environment
D. A macro

Answer: C
Explanation
: Closures are nameless functions that can grab variables from their surroundings, like |x| x + 1.


45. How do you define a closure that adds 2 to a number?

A. let add = fn(x) { x + 2 };
B. let add = |x| x + 2;
C. fn add(x) = x + 2;
D. let add = x => x + 2;

Answer: B
Explanation
: Closures use |args| expression, so |x| x + 2 is the right syntax.


46. Which macro prints values in debug format?

A. print!
B. println!
C. eprintln!
D. println!(“{:?}”, …)

Answer: D
Explanation
: {:?} with println! prints debug output for types implementing Debug.


47. What does #[derive(Debug)] do?

A. Adds debug info to compiled code
B. Enables debug logging
C. Auto-implements the Debug trait
D. Formats code

Answer: C
Explanation
: #[derive(Debug)] lets a struct or enum be printed with {:?} by implementing Debug.


48. What’s shadowing in Rust?

A. Accessing global variables
B. Re-declaring a variable with a new value
C. Using unsafe code
D. Borrowing across scopes

Answer: B
Explanation
: Shadowing lets you reuse a variable name with a new declaration, like let x = 5; let x = 10;.


49. What’s the key feature of match?

A. Only checks integers
B. Requires else
C. Ensures all patterns are handled
D. Allows partial checks

Answer: C
Explanation
: match forces you to cover every possible case, making it exhaustive and safe.


50. How do you use a module in utils.rs from main.rs?

A. include!(“utils.rs”);
B. use utils;
C. mod utils; in main.rs, with utils.rs as the file
D. extern mod utils;

Answer: C
Explanation:
Declare mod utils; in main.rs, and Rust looks for utils.rs to load the module.


Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *