Rust Beginner Quiz
30 questions on Rust Programming.
Question 1: Which keyword allows a variable to be mutable in Rust?
- A. mutable
- B. let
- C. mut β (correct answer)
- D. var
Explanation: By default, variables in Rust are immutable. Prepending the mut keyword during variable declaration makes them mutable.
Question 2: What is the entry point function of every executable Rust program?
- A. start()
- B. begin()
- C. main() β (correct answer)
- D. run()
Explanation: Every executable Rust program requires a main() function, which acts as the entry point of execution.
Question 3: What is standard package manager and build system for Rust?
- A. npm
- B. pip
- C. cargo β (correct answer)
- D. gem
Explanation: cargo is Rust's official package manager, build system, and dependency manager.
Question 4: What will be the output of the following Rust code?
``rust
fn main() {
let x = 5;
// x = 10;
println!("{}", x);
}
``
- A. 5 β (correct answer)
- B. 10
- C. Compiler Error
- D. Garbage Value
Explanation: The reassignment x = 10 is commented out. x is declared as an immutable variable with the value 5, which is printed.
Question 5: Which core concept in Rust manages memory safety without using a garbage collector?
- A. Reference Counting
- B. Ownership and Borrowing β (correct answer)
- C. Virtual Machine Sandboxing
- D. Struct Interfaces
Explanation: Rust uses an Ownership system with compiler-enforced borrowing rules to guarantee memory safety at compile-time without a garbage collector.
Question 6: What happens when you assign a non-copyable variable to another variable in Rust?
- A. The value is duplicated
- B. The ownership of the value is moved β (correct answer)
- C. A reference is created
- D. Compiler error occurs immediately
Explanation: By default, assignment of variables that do not implement the Copy trait moves the ownership, making the original variable invalid.
Question 7: How do you declare a read-only reference (borrow) in Rust?
- A. &var β (correct answer)
- B. *var
- C. ref var
- D. mut &var
Explanation: The ampersand & denotes a reference. &var creates an immutable borrow, allowing reading of the value without taking ownership.
Question 8: Which macro is used to print formatted output to console in Rust?
- A. print()
- B. println!() β (correct answer)
- C. format!()
- D. log!()
Explanation: In Rust, macros end with an exclamation mark. println!() prints formatted text followed by a newline to standard output.
Question 9: Which composite type represents a growable, heap-allocated array in Rust?
- A. Array
- B. Vector (Vec<T>) β (correct answer)
- C. Slice
- D. Tuple
Explanation: A vector Vec<T> is a dynamic, growable array stored on the heap. Standard arrays [T; N] have fixed length and are usually stack-allocated.
Question 10: Which keyword is used to return a value from a match arm or test multiple conditions in Rust?
- A. switch
- B. match β (correct answer)
- C. select
- D. choose
Explanation: Rust's match statement is an extremely powerful control flow construct that performs pattern matching on values.
Question 11: What is the result of the following match block?
``rust
fn main() {
let x = Some(5);
match x {
Some(i) => println!("{}", i),
None => println!("None"),
}
}
``
- A. Some(5)
- B. 5 β (correct answer)
- C. None
- D. Compiler Error
Explanation: The pattern Some(i) matches Some(5), binding i to 5. The print statement prints 5.
Question 12: How are errors represented in Rust for operations that can fail but are recoverable?
- A. Try/Catch exceptions
- B. Result<T, E> enum β (correct answer)
- C. Panic macro
- D. nil pointer returns
Explanation: Rust does not have exception handling. Recoverable errors are handled using the Result<T, E> enum, which is either Ok(T) or Err(E).
Question 13: Which keyword is used to declare a constant in Rust?
- A. let
- B. const β (correct answer)
- C. static
- D. final
Explanation: The const keyword declares constant values which must have explicit type annotations and be evaluated at compile-time.
Question 14: What is the size of the char type in Rust?
- A. 1 byte
- B. 2 bytes
- C. 4 bytes β (correct answer)
- D. 8 bytes
Explanation: A char in Rust represents a Unicode scalar value, which is 4 bytes (32 bits) in size, allowing it to store emojis and non-ASCII glyphs natively.
Question 15: What will happen if the code below is executed?
``rust
fn main() {
let v = vec![1, 2, 3];
println!("{}", v[99]);
}
``
- A. Prints 0
- B. Returns None
- C. The program panics (crashes safely) β (correct answer)
- D. Garbage value is printed
Explanation: Accessing a vector index out of bounds using the brackets index operator [] causes the program to panic and exit immediately to prevent invalid memory reads.
Question 16: What is the output of the following Rust code?
``rust
fn main() {
let s1 = String::from("hello");
let s2 = s1;
// println!("{}", s1);
println!("{}", s2);
}
``
- A. hello β (correct answer)
- B. hello hello
- C. Compiler Error
- D. Garbage Value
Explanation: The code prints "hello". The line // println!("{}", s1); is commented out. If it were active, it would cause a compiler error because ownership of the String was moved to s2.
Question 17: Which of the following describes Rust's borrowing rules?
- A. Any number of mutable references at a time
- B. Either many immutable references OR exactly one mutable reference at a time β (correct answer)
- C. One mutable and one immutable reference concurrently
- D. References must be declared static
Explanation: To prevent data races at compile-time, Rust allows you to have either any number of immutable references (&T) OR exactly one mutable reference (&mut T) at any given time.
Question 18: What is the purpose of the Option<T> enum in Rust?
- A. To configure compiler optimizations
- B. To represent a value that could be either something (
Some(T)) or nothing (None) β (correct answer)
- C. To handle multithreaded channels
- D. To define optional structure fields
Explanation: Rust has no null values. Nullable types are modeled using the Option<T> enum, which contains either Some(T) or None.
Question 19: Which operator is used to extract the value from a Result or Option or return early if it is an error?
- A. ? β (correct answer)
- B. !
- C. .
- D. *
Explanation: The question mark ? operator is a shorthand for matching on a Result or Option. It unpacks successful values or propagates failures by returning them early.
Question 20: How do you implement methods on a struct in Rust?
- A. Declaring them inside the
struct braces
- B. Using an
impl block with the struct name β (correct answer)
- C. Declaring them inside a
trait only
- D. Methods are not supported on structs
Explanation: In Rust, structure fields are declared in a struct block, and their actions/methods are defined separately within an impl (implementation) block.
Question 21: What does the #[derive(Debug)] attribute do on a struct?
- A. Automatically enables compiler debugging logging
- B. Implements the
Debug trait so the struct can be printed with {:?} β (correct answer)
- C. Makes all fields mutable
- D. Speeds up cargo builds
Explanation: The derive attribute instructs the compiler to generate standard default implementations for traits like Debug, enabling formatted debugging outputs.
Question 22: What is the difference between String and &str in Rust?
- A.
String is heap-allocated and growable; &str is an immutable reference/slice to string data β (correct answer)
- B. They are identical
- C.
&str is slower
- D.
String is deprecated
Explanation: String is owned, heap-allocated, and growable. &str is a string slice representing a read-only view of a sequence of UTF-8 bytes (often stack-allocated or pointing to binary segments).
Question 23: What will be the output of the following Rust code?
``rust
fn main() {
let x = 5;
let y = x;
println!("{} {}", x, y);
}
``
- A. 5 5 β (correct answer)
- B. 5
- C. Compiler Error
- D. Garbage Value
Explanation: Since i32 (default integer type) implements the Copy trait, let y = x; duplicates the value of x rather than moving ownership. Both variables remain valid.
Question 24: Which keyword is used to import packages or modules into scope?
- A. import
- B. include
- C. use β (correct answer)
- D. require
Explanation: The use keyword brings paths (like packages, structs, or functions) into the current scope.
Question 25: What is a closure in Rust?
- A. An anonymous function that can capture variables from its environment β (correct answer)
- B. A class definition
- C. A database connection pool
- D. A loop terminator
Explanation: Closures are anonymous functions (declared with pipe || syntax) that can capture values from the scope in which they are defined.
Question 26: What is the lifetime annotation syntax in Rust?
- A.
a:
- B.
'a β (correct answer)
- C.
<lifetime>
- D.
@a
Explanation: Lifetimes in Rust are declared using a single tick prefix followed by a name, conventionally 'a, 'b, etc. They are compile-time markers validating that references don't outlive their referents.
Question 27: What is the output of the following Rust code?
``rust
fn main() {
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", x);
}
``
- A. 5
- B. 6 β (correct answer)
- C. Compiler Error
- D. Garbage Value
Explanation: Inside the inner scope, y is a mutable reference to x. De-referencing y with * modifies x's value. The inner block ends, releasing y's borrow, so x can be printed normally as 6.
Question 28: What is a Trait in Rust?
- A. A class inheritance construct
- B. A definition of shared behavior that types can implement (similar to interfaces) β (correct answer)
- C. A compile-time constant
- D. A thread safety lock
Explanation: A trait tells the Rust compiler about functionality a particular type has and can share with other types. It is similar to interfaces in Java/C#.
Question 29: What is the difference between unwrap() and expect() when handling Options or Results?
- A.
expect allows specifying a custom panic error message on failure β (correct answer)
- B.
unwrap is safer
- C. They are identical
- D.
expect is deprecated
Explanation: Both crash the program if a None or Err value is present. However, expect(msg) lets you provide a clear diagnostic error message, making debugging easier.
Question 30: What does the Arc pointer stand for in Rust?
- A. Automatic Reference Counter
- B. Atomically Reference Counted pointer (thread-safe shared reference) β (correct answer)
- C. Array Record Collection
- D. Advanced Runtime Compiler
Explanation: Arc<T> is a thread-safe atomically reference-counted pointer used to share read-only ownership of data across threads safely. Rc<T> is for single-threaded only.