




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































Question 1. Which of the following is the primary reason developers choose Rust for system programming? A) Automatic garbage collection B) Memory safety without a runtime overhead C) Dynamic typing D) Built‑in GUI framework Answer: B Explanation: Rust guarantees memory safety through its ownership model at compile time, eliminating the need for a garbage collector and keeping runtime overhead minimal. Question 2. In a new Rust project, which command creates a binary crate with the default directory layout? A) rustc new my_project B) cargo init my_project C) cargo new my_project --bin D) cargo create my_project Answer: C Explanation: cargo new <name> --bin creates a new binary crate (executable) with a src/main.rs file and a Cargo.toml. Question 3. What does the following line print? println!("The answer is {}", 42); A) The answer is {42} B) The answer is 42 C) The answer is {} D) Compilation error Answer: B
Explanation: {} is a placeholder for the argument 42, so the formatted string becomes “The answer is 42”. Question 4. Which keyword makes a variable mutable in Rust? A) const B) let mutable C) var D) mut Answer: D Explanation: mut placed after let (e.g., let mut x = 5;) allows the variable’s value to be changed. Question 5. What is the value of x after executing the code below?
let x = 5; let x = x + 1; let x = x * 2; A) 5 B) 6 C) 12 D) 11 Answer: C Explanation: Each let shadows the previous binding. First x becomes 5, then 6, then 12. Question 6. Which of the following statements about constants (const) in Rust is true?
A) 'ab' B) "a" C) 'a' D) a Answer: C Explanation: A char literal is a single Unicode scalar value surrounded by single quotes. Question 10. How do you create a tuple containing an i32, a bool, and a char? A) (i32, bool, char) B) [i32, bool, char] C) (5, true, 'c') D) Tuple::new(5, true, 'c') Answer: C Explanation: Tuple values are written as comma‑separated elements inside parentheses. Question 11. Which syntax creates an array of five f64 values all initialized to 0.0? A) [0.0; 5] B) vec![0.0; 5] C) Array::new(5, 0.0) D) {0.0, 0.0, 0.0, 0.0, 0.0} Answer: A Explanation: [value; count] creates an array with count copies of value. Question 12. What will the compiler infer as the type of let x = 10; if no further context is given?
A) i B) i C) i D) usize Answer: B Explanation: By default, integer literals without suffix default to i32. Question 13. Which of the following is a correct function definition that returns an i32? A) fn add(a: i32, b: i32) - > i32 { a + b } B) fn add(a, b) { a + b } C) fn add(a: i32, b: i32) { return a + b; } D) fn add(a: i32, b: i32) - > i32; Answer: A Explanation: The function includes parameter types, a return type annotation, and an expression body that evaluates to i32. Question 14. In Rust, the difference between a statement and an expression is that: A) Statements can return values, expressions cannot. B) Expressions always end with a semicolon. C) Statements do not produce a value, while expressions do. D) There is no difference; they are synonyms. Answer: C Explanation: An expression evaluates to a value; a statement performs an action and yields no value.
Answer: D Explanation: The break statement can return a value from a loop; here it returns counter when it reaches 3. Question 18. Which of the following correctly iterates over the numbers 0, 1, 2 using a for loop? A) for i in 0..3 { println!("{}", i); } B) for i in 0..=3 { println!("{}", i); } C) for i in [0,1,2] {} D) for i in 0..2 {} Answer: A Explanation: 0..3 is a range that yields 0, 1, 2 (exclusive upper bound). Question 19. In Rust’s ownership model, which rule is NOT correct? A) Each value has a single owner. B) When the owner goes out of scope, the value is dropped. C) Multiple mutable references to the same data are allowed simultaneously. D) Data can be borrowed immutably many times. Answer: C Explanation: Only one mutable reference (or any number of immutable references) may exist at a time.
Question 20. What happens when a variable that owns heap data goes out of scope? A) Memory is leaked. B) The data is automatically freed (dropped). C) The compiler raises an error. D) The variable becomes a dangling pointer. Answer: B Explanation: Rust’s Drop trait runs automatically, freeing heap memory when the owner is dropped. Question 21. Which trait must be implemented to enable deep copying of a type? A) Copy B) Clone C) Borrow D) Default Answer: B Explanation: Clone provides a clone() method for explicit deep copies; Copy is for cheap bitwise copies. Question 22. Which of the following creates an immutable reference to a String named s? A) let r = &mut s; B) let r = s; C) let r = &s; D) let r = Box::new(s); Answer: C
Answer: B Explanation: Tuple structs are instantiated like regular tuple syntax but with the struct name. Question 26. What is the output of the following code?
struct Counter { count: i32 } impl Counter { fn inc(&mut self) { self.count += 1; } } let mut c = Counter { count: 0 }; c.inc(); println!("{}", c.count); A) 0 B) 1 C) Compilation error D) Runtime panic Answer: B Explanation: inc mutably borrows self and increments count; the printed value is 1. Question 27. Which of the following defines an enum with variants Ok holding a i32 and Err holding a String? A) enum Result { Ok(i32), Err(String) } B) enum Result { Ok = i32, Err = String } C) enum Result { Ok(i32); Err(String); }
D) enum Result { Ok(i32) | Err(String) } Answer: A Explanation: Enum variants can carry data; the syntax is Variant(Type). Question 28. In a match expression, which pattern matches any value and binds it to a variable named val? A) _ B) val C) ref val D) val @ _ Answer: D Explanation: val @ _ captures the matched value into val while _ discards it. Question 29. What does the Option<T> enum represent in Rust? A) A value that may be either Some(T) or None. B) An error handling type similar to Result. C) A mutable reference wrapper. D) A collection of unique keys. Answer: A Explanation: Option<T> is used for values that may be absent (None) or present (Some(value)). Question 30. Which method extracts the inner value from Option<i32> safely, providing a default of 0 if None? A) unwrap_or(0) B) expect("msg")
D) Compile‑time error. Answer: C Explanation: Indexing a vector out of bounds triggers a panic at runtime. Question 34. Which of the following correctly iterates over a vector v by reference? A) for x in v {} B) for x in &v {} C) for x in v.iter() {} D) Both B and C are correct. Answer: D Explanation: &v yields an iterator of references; v.iter() does the same explicitly. Question 35. What is the difference between String and &str? A) String is mutable heap‑allocated data; &str is an immutable view into a string slice. B) String is always UTF‑8, &str is ASCII only. C) String is a compile‑time constant, &str is runtime. D) There is no difference; they are aliases. Answer: A Explanation: String owns its data and can be mutated; &str is a borrowed slice. Question 36. Which method converts a &str into an owned String? A) to_string() B) as_string() C) into_string() D) clone()
Answer: A Explanation: to_string() (or String::from) creates an owned String from a string slice. Question 37. In a HashMap<K, V>, which trait must the key type K implement? A) Copy B) Eq and Hash C) Ord D) Clone Answer: B Explanation: Hash maps require keys to be hashable (Hash) and comparable for equality (Eq). Question 38. Which statement about the Result<T, E> enum is correct? A) Ok holds an error, Err holds a success value. B) Result can only be used with I/O operations. C) Ok contains a success value, Err contains an error. D) Result automatically retries failed operations. Answer: C Explanation: Result distinguishes successful outcomes (Ok) from failures (Err). Question 39. How do you propagate an error using the ? operator inside a function that returns Result<T, E>? A) let v = some_func()?; B) let v = some_func().unwrap(); C) let v = some_func().expect("error"); D) let v = some_func().ok();
Answer: B Explanation: The [dependencies] table lists crates that the project depends on. Question 43. What is the purpose of the use keyword in Rust? A) To import external crates only. B) To bring a module, trait, or function into the current scope. C) To declare a new variable. D) To create a new crate. Answer: B Explanation: use allows items to be referenced without their full path. Question 44. Which statement correctly distinguishes a package from a crate? A) A package may contain multiple crates; a crate is a single compilation unit. B) A crate contains many packages. C) Packages and crates are synonymous. D) Packages are only for libraries, crates only for binaries. Answer: A Explanation: A Cargo package can include one library crate and/or multiple binary crates. Question 45. How do you declare a module named utils in a file src/utils.rs? A) mod utils; placed in main.rs or lib.rs. B) pub utils; in main.rs. C) module utils; in utils.rs. D) use utils; in main.rs. Answer: A
Explanation: mod utils; tells the compiler to load src/utils.rs as a submodule. Question 46. Which attribute marks a function as a test that Cargo will run with cargo test? A) #[bench] B) #[test] C) #[example] D) #[run] Answer: B Explanation: The #[test] attribute registers the function as a test case. Question 47. What is the effect of adding #![allow(dead_code)] at the top of a Rust file? A) It disables all warnings. B) It permits compilation of code that is never called without warning. C) It forces the compiler to treat dead code as errors. D) It automatically removes dead code during compilation. Answer: B Explanation: The allow attribute suppresses the dead‑code warning. Question 48. Which of the following is a valid way to create a reference that lives for the entire program? A) let r: &'static str = "hello"; B) let r = &String::from("hello"); C) let r = Box::leak(Box::new(5)); D) Both A and C are valid. Answer: D
B) Casts a to the type u8 at compile time. C) Moves ownership of a into b. D) Creates a reference to a. Answer: B Explanation: as performs a numeric cast (or pointer cast) from one type to another. Question 53. Which of the following statements about the Copy trait is true? A) Types that implement Copy are moved when assigned. B) Copy can be derived for types containing a String. C) Copy types are duplicated bitwise without a call to clone(). D) Copy requires the type to implement Drop. Answer: C Explanation: Copy enables implicit shallow copies; it cannot be derived for types that own heap memory like String. Question 54. Consider the code:
let v = vec![1, 2, 3]; let v2 = v; println!("{:?}", v); What happens at compile time? A) The program prints [1, 2, 3]. B) The program compiles but panics at runtime. C) The compiler reports a use‑after‑move error.
D) The code silently clones v. Answer: C Explanation: Vec<T> does not implement Copy; assigning v to v2 moves ownership, making v invalid. Question 55. Which pattern matches a Result<T, E> that is an Ok variant and binds the inner value to val? A) Result::Ok(val) B) Ok(val) C) val @ Ok(_) D) Some(val) Answer: B Explanation: In a match, Ok(val) directly matches the Ok variant and binds the payload. Question 56. What is the output of the following code?
fn main() { let mut s = String::from("abc"); let r1 = &s; let r2 = &s; // let r3 = &mut s; // uncommenting this line causes an error println!("{} {}", r1, r2); } A) abc abc B) Compilation error because of mutable borrow.