




























































































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 Cargo command creates a new library package? A) cargo new --bin my_lib B) cargo init --lib my_lib C) cargo new --lib my_lib D) cargo build --lib my_lib Answer: C Explanation: cargo new --lib <name> scaffolds a new library crate, generating a src/lib.rs file. Question 2. In Cargo.toml, what does the caret (^) symbol in a version requirement mean? A) Accept any version greater than the specified one B) Accept only the exact version specified C) Accept versions that do not modify the left‑most non‑zero digit D) Accept versions that are lower than the specified one Answer: C Explanation: The caret allows semver‑compatible updates, i.e., it permits changes that do not modify the left‑most non‑zero digit. Question 3. Which profile does Cargo use when you run cargo run --release? A) dev B) test C) bench D) release Answer: D Explanation: The --release flag tells Cargo to compile using the release profile, which enables optimizations.
Question 4. What does the rustup component add clippy command do? A) Installs the Clippy linter for the current toolchain B) Enables Clippy warnings in the compiler output automatically C) Replaces rustc with the Clippy compiler D) Generates a new Cargo project pre‑configured with Clippy Answer: A Explanation: rustup component add clippy adds the Clippy component (the linting tool) to the active toolchain. Question 5. In a Cargo workspace, which file defines the members of the workspace? A) Cargo.lock B) Cargo.toml at the workspace root C) workspace.toml D) .cargo/config.toml Answer: B Explanation: The root Cargo.toml contains a [workspace] table listing the member package paths. Question 6. Which of the following statements about mut bindings is true? A) A mutable binding can be reassigned but its interior data is always immutable B) mut only affects the binding, not the underlying value’s mutability C) mut makes both the binding and the underlying value mutable for all references D) mut can be applied to constants declared with const Answer: B
D) Compilation error because of type mismatch Answer: B Explanation: Integer division truncates toward zero, so 5 / 2 yields 2. Question 10. Which pattern matches any value and binds it to a variable named x? A) _ B) x @ _ C) x D) ref x Answer: C Explanation: A bare identifier pattern (x) matches any value and binds it to x. Question 11. In a match expression, what does the ref keyword do? A) Forces the matched value to be moved out of the pattern B) Creates an immutable reference to the matched part C) Creates a mutable reference to the matched part D) Allows pattern matching on reference types only Answer: B Explanation: ref binds a reference to the matched data without moving it. Question 12. Which of the following loops can be labeled and later broken out of using break 'label? A) for only B) while only C) loop only
D) All three (for, while, loop) Answer: D Explanation: Any of Rust’s loop constructs can be given a label and broken out of with break 'label. Question 13. What is the return type of a function that never returns normally (e.g., calls panic!)? A) () B) ! C) Result<(), E> D) Option<T> Answer: B Explanation: The never type ! denotes functions that do not return to the caller. Question 14. Which attribute makes a function evaluable at compile time? A) #[inline] B) #[test] C) #[const_fn] (deprecated) D) const fn keyword Answer: D Explanation: Declaring a function with const fn allows it to be called in constant contexts. Question 15. Which of the following statements about the ownership rule “each value has a single owner” is false? A) Ownership can be transferred via move semantics B) Multiple immutable references can coexist with the owner
C) The data pointed to will never be moved D) The reference can be sent across threads without Sync Answer: A Explanation: Rust’s borrowing rules enforce exclusive access for mutable references. Question 19. Which of the following lifetimes is the longest possible? A) 'a where 'a is a function parameter lifetime B) 'static C) An inferred lifetime from a local variable D) 'b where 'b is tied to a temporary value Answer: B Explanation: 'static lives for the entire duration of the program. Question 20. When is it necessary to write an explicit lifetime annotation on a function signature? A) When the function returns a reference that does not come from its parameters B) When the function takes a generic type parameter C) When the function has no reference parameters D) When the function returns a String Answer: A Explanation: If the returned reference is tied to an input reference, the compiler cannot infer the relationship and requires an explicit lifetime. Question 21. Which smart pointer provides shared ownership with compile‑time reference counting? A) Box<T>
B) Rc<T> C) Arc<T> D) RefCell<T> Answer: B Explanation: Rc<T> enables multiple owners in a single‑threaded context using reference counting. Question 22. Which smart pointer is safe to share across threads? A) Rc<T> B RefCell<T> C) Arc<T> D) Box<T> (without Send) Answer: C Explanation: Arc<T> (Atomic Reference Counted) is designed for thread‑safe shared ownership. Question 23. What is the primary purpose of RefCell<T>? A) Provide compile‑time mutable borrowing checks B) Enable interior mutability with runtime borrow checking C) Allow shared mutable access without any checks D) Replace Box<T> for heap allocation Answer: B Explanation: RefCell<T> enforces borrowing rules at runtime, allowing mutable access through immutable references. Question 24. Which trait must a type implement to be used as a key in a HashMap?
Question 27. How can you implement a trait for a type you do not own? A) By using a blanket implementation in the standard library B) By creating a newtype wrapper around the foreign type C) By adding #[allow(orphan)] attribute D) It is impossible; Rust forbids it Answer: B Explanation: The “orphan rule” prevents implementing external traits on external types directly; wrapping the type in a local newtype circumvents this. Question 28. Which syntax declares a generic function that works for any type implementing Clone? A) fn foo<T>(x: T) where T: Clone {} B) fn foo<T: Clone>(x: T) {} C) Both A and B are correct D) Neither; you must use impl Clone Answer: C Explanation: Both the where clause and the inline bound are valid ways to constrain generics. Question 29. What is the difference between impl Trait in argument position and dyn Trait? A) impl Trait uses static dispatch; dyn Trait uses dynamic dispatch B) impl Trait can only be used for lifetimes, not traits C) dyn Trait requires the type to be sized D) There is no difference; they are synonyms Answer: A
Explanation: impl Trait in parameters results in monomorphization (static dispatch), whereas dyn Trait creates a trait object for dynamic dispatch. Question 30. Which of the following is a correct way to create a boxed slice from a vector? A) let b = Box::new(vec![1,2,3]); B) let b: Box<[i32]> = vec![1,2,3].into_boxed_slice(); C) let b = Box::from(vec![1,2,3]); D) let b = Box::new([1,2,3]); Answer: B Explanation: Vec<T>::into_boxed_slice() consumes the vector and returns a Box<[T]>. Question 31. Which trait provides the clone() method? A) Copy B) Clone C) Default D) Debug Answer: B Explanation: The Clone trait defines the clone() method for explicit deep copies. Question 32. What does the #[must_use] attribute on a function indicate? A) The compiler will error if the function’s return value is ignored B) The function must be called at least once in the program C) The function’s side effects are undefined if not used D) The function can only be used in unsafe blocks Answer: A
D) enumerate Answer: B Explanation: filter returns an iterator that yields only elements satisfying the predicate. Question 36. What does the Iterator::fold method do? A) Converts an iterator into a vector B) Applies a function to each element, accumulating a single result C) Returns the first element that matches a condition D) Reverses the order of elements in the iterator Answer: B Explanation: fold takes an initial accumulator and a closure, producing a single aggregated value. Question 37. Which collection automatically grows its capacity when elements are pushed beyond its current size? A) Vec<T> B) HashMap<K,V> C) VecDeque<T> D) All of the above Answer: D Explanation: All three dynamically resize when needed. Question 38. What is the time complexity of inserting a key into a HashMap in the average case? A) O(1) amortized B) O(log n)
C) O(n) D) O(n log n) Answer: A Explanation: HashMap insertions are constant‑time on average, assuming a good hash function. Question 39. Which method on String returns a slice (&str) of the whole string without allocating? A) to_string() B) as_str() C) clone() D) into_bytes() Answer: B Explanation: as_str() borrows the String as a &str. Question 40. Which of the following creates a double‑ended queue that can push and pop from both ends efficiently? A) Vec<T> B) LinkedList<T> C) VecDeque<T> D) HashSet<T> Answer: C Explanation: VecDeque is implemented as a ring buffer, providing O(1) push/pop at both ends. Question 41. What does the thread::spawn function return? A) Thread handle that can be joined
Question 44. Which of the following ensures that multiple threads can read a value concurrently while allowing only one writer at a time? A) Arc<Mutex<T>> B) Arc<RwLock<T>> C) Mutex<T> alone D) RefCell<T> Answer: B Explanation: RwLock provides shared read access and exclusive write access. Question 45. When is it appropriate to use unsafe in Rust? A) To bypass the borrow checker for performance when you can guarantee safety manually B) To allocate memory on the heap without Box C) To automatically derive Clone for a type D) To call any standard library function that returns Result Answer: A Explanation: unsafe blocks allow operations that the compiler cannot verify, requiring the programmer to uphold safety invariants. Question 46. Which keyword is used to declare an external C function in Rust? A) extern "C" B) foreign fn C) cdecl D) #[link] Answer: A Explanation: extern "C" defines a block of foreign function declarations using the C ABI.
Question 47. What does the macro_rules! macro system allow you to define? A) Procedural macros that run at compile time B) Declarative macros based on pattern matching of token trees C) Inline assembly blocks D) Automatic trait implementations for all types Answer: B Explanation: macro_rules! creates declarative macros by matching input token patterns. Question 48. Which attribute is required to export a Rust function with C linkage? A) #[no_mangle] B) #[export_name = "my_func"] C) #[repr(C)] D) #[link_name = "my_func"] Answer: A Explanation: #[no_mangle] prevents the compiler from changing the symbol name, making it visible to C linkers. Question 49. Which of the following statements about the Result<T, E> type is true? A) It implements Iterator automatically B) It can be used with the ? operator to propagate errors C) It is only available in the std::error module D) It always contains a value of type T Answer: B Explanation: The ? operator works on Result, returning early with the Err value if present.
Answer: A Explanation: thiserror uses #[derive(Error)] and #[error(...)] attributes to implement Error and Display. Question 53. Which method on Option<T> converts the option into a Result<T, E> using a supplied error value? A) ok_or B) unwrap_or C) as_ref D) transpose Answer: A Explanation: ok_or(err) turns Some(v) into Ok(v) and None into Err(err). Question 54. What does the collect() method do when called on an iterator of (K, V) pairs? A) Returns a Vec<(K, V)> B) Returns a HashMap<K, V> if the target type is inferred as such C) Returns a tuple of two vectors, one for keys and one for values D) Consumes the iterator without producing any collection Answer: B Explanation: collect() can build any collection that implements FromIterator; for (K, V) it can produce a HashMap. Question 55. Which of the following is true about String::push_str? A) It takes ownership of the argument string slice B) It appends a &str without allocating if there is enough capacity
C) It creates a new String and returns it D) It can only be called on a &mut &str Answer: B Explanation: push_str appends a borrowed string slice, reallocating only if needed. Question 56. What is the result of vec![0; 5].into_iter().sum::<i32>()? A) 0 B) 5 C) 25 D) Compilation error because sum needs a Iterator<Item = i32> Answer: B Explanation: The iterator yields five zeros; their sum is 0. However, the type annotation ::<i32> forces the sum to be i32. Since all elements are 0, the result is 0. Correction: The correct answer is A. Explanation: Each element is 0, so the total sum is 0. Question 57. Which method on Vec<T> removes and returns the last element, if any? A) pop B) remove C) truncate D) clear Answer: A Explanation: pop takes the last element and returns Option<T>. Question 58. In a match expression, what does the pattern Some(ref mut x) do?