Q1. What file extension is used for Rust source files?
Rust source files commonly use a short two-letter extension.
Answer: .rs — Rust source files conventionally use the .rs extension.
Q2. Which tool is the Rust package manager and build system?
Used to build, test, run, and publish crates.
Answer: cargo — Cargo manages dependencies, builds projects, runs tests, and publishes crates.
Q3. Which command compiles a Rust package in the current directory?
Builds the project without running it.
Answer: cargo build — compiles the package and produces an executable or library in target/ directory.
Q4. Fill: The entry point of a Rust program is
Function named main with fn keyword.
Answer: fn main() — `fn main() {}` is the program entry point in Rust.
Q5. Which keyword declares an immutable variable?
Default bindings are immutable unless specified otherwise.
Answer: let — `let x = 5;` creates an immutable binding; use `let mut x = 5;` for mutability.
Q6. Which keyword makes a variable mutable?
Used together with let: let mut x = ...
Answer: mut — `let mut x = 1;` declares x as mutable.
Q7. Which macro prints to standard output with a newline?
Macro name ends with an exclamation mark.
Answer: println! — prints formatted text followed by a newline.
Q8. Which type is an owned, growable UTF-8 string?
Owned heap-allocated string type.
Answer: String — an owned, growable UTF-8 string; `&str` is a borrowed string slice.
Q9. Which type is a borrowed string slice?
Immutable view into a string.
Answer: &str — borrowed string slice referencing UTF-8 data; often seen as function parameters.
Q10. Which collection is a growable array type in Rust?
Common dynamic array in Rust standard library.
Answer: Vec<T> — a heap-allocated, growable array type; use vec![] to create one.
Q11. Which keyword expresses ownership transfer into a closure or thread?
Used before closure parameters.
Answer: move — `move || { ... }` forces the closure to take ownership of captured variables.
Q12. Fill: Borrowing a reference to x is written as
let x = 5;
let r = ;
let r = ;
Use ampersand to borrow immutably.
Answer: &x — `let r = &x;` borrows x immutably; `&mut x` borrows mutably.
Q13. Which concept prevents data races by enforcing ownership rules at compile time?
Compile-time enforcement of borrowing and ownership rules.
Answer: borrow checker — Rust's borrow checker enforces ownership and borrowing rules to prevent data races and invalid memory access.
Q14. Which enum is commonly used to represent optional values?
Variants are Some and None.
Answer: Option<T> — `Option` has variants `Some(T)` and `None` to represent presence or absence of a value.
Q15. Which enum is used for fallible operations returning either Ok or Err?
Variants are Ok and Err.
Answer: Result<T, E> — used to return success (`Ok`) or error (`Err`) values from functions.
Q16. Which method converts a Result to a value or panics with a message?
Provides a custom panic message on Err.
Answer: expect() — `result.expect("msg")` returns the Ok value or panics with the provided message on Err.
Q17. Which keyword declares a struct type?
Defines a composite data type with named fields.
Answer: struct — `struct Point { x: i32, y: i32 }` defines a struct type.
Q18. How do you implement methods for a struct Point?
Use impl block with the type name.
Answer: impl Point { fn ... } — methods for Point are defined inside an `impl Point { ... }` block.
Q19. Which trait is used for formatting with {:?}?
Derive with #[derive(Debug)].
Answer: Debug — `{:?}` uses the Debug trait; implement or derive Debug to enable debug formatting.
Q20. Which trait is used for user-facing formatting with {}?
Implement fmt::Display for pretty printing.
Answer: Display — `{}` uses the Display trait; implement fmt::Display for custom user-facing formatting.
Q21. Which keyword defines a generic type parameter in Rust?
Angle brackets after type or function name.
Answer: <T> — generics are declared with angle brackets, e.g., `fn foo(x: T) {}`.
Q22. Which keyword declares a trait (similar to interfaces)?
Traits define shared behavior for types.
Answer: trait — `trait Drawable { fn draw(&self); }` defines behavior that types can implement.
Q23. Which syntax implements a trait for a type?
Use impl followed by trait and for keyword.
Answer: impl Trait for Type { ... } — implements Trait methods for Type.
Q24. Which macro creates a vector from a list of elements?
Common macro for creating Vecs.
Answer: vec! — `vec![1, 2, 3]` creates a Vec<i32> with those elements.
Q25. Which keyword marks code as unsafe, allowing raw pointers and unchecked operations?
Use with caution and explicit unsafe blocks.
Answer: unsafe — `unsafe { ... }` allows operations that the compiler cannot guarantee are safe.
Q26. Which smart pointer provides shared ownership with reference counting (single-threaded)?
Rc is for single-threaded reference counting.
Answer: Rc<T> — reference-counted pointer for shared ownership in single-threaded contexts; Arc is thread-safe variant.
Q27. Which smart pointer provides thread-safe reference counting?
Arc stands for atomic reference counting.
Answer: Arc<T> — atomic reference-counted pointer for sharing across threads.
Q28. Which pointer type allocates a value on the heap and provides unique ownership?
Box provides heap allocation and ownership transfer.
Answer: Box<T> — allocates T on the heap and provides unique ownership semantics.
Q29. Which type allows interior mutability checked at runtime?
RefCell enforces borrow rules at runtime for single-threaded contexts.
Answer: RefCell<T> — allows mutable borrows checked at runtime (panic on violation); often combined with Rc for shared ownership.
Q30. Which macro is used to create formatted strings without printing?
Returns a String with formatted content.
Answer: format! — creates a String using formatting syntax, e.g., `format!("x = {}", x)`.
Q31. Which keyword introduces pattern matching with multiple arms?
match arms can destructure enums and tuples.
Answer: match — `match value { pattern1 => expr1, pattern2 => expr2, _ => default }`.
Q32. Which construct is used for conditional destructuring of an Option?
Concise way to handle Some variant.
Answer: if let — `if let Some(x) = opt { ... }` handles the Some case concisely.
Q33. Which iterator adaptor transforms each element using a closure?
Applies a function to each iterator item.
Answer: map() — `iter.map(|x| x * 2)` transforms elements lazily.
Q34. Which method collects iterator results into a collection like Vec?
Often used with turbofish to specify target type.
Answer: collect() — `iter.map(...).collect::>()` gathers iterator items into a Vec or other collection.
Q35. Which keyword declares a constant value with static lifetime?
static creates a global with a fixed address; const is inlined.
Answer: static — `static NAME: &str = "value";` declares a global with static lifetime; `const` is a compile-time constant.
Q36. Which attribute derives common traits like Debug and Clone automatically?
Placed above struct or enum definitions.
Answer: #[derive(...)] — e.g., `#[derive(Debug, Clone)]` automatically implements those traits.
Q37. Which command runs tests in a Cargo project?
Runs unit and integration tests defined in the project.
Answer: cargo test — executes tests in the current Cargo package.
Q38. Which attribute marks a function as a test?
Placed above test functions in test modules.
Answer: #[test] — marks a function as a unit test to be run by `cargo test`.
Q39. Which module provides threading primitives like spawn?
Use thread::spawn to run code concurrently.
Answer: std::thread — `std::thread::spawn(|| { ... })` starts a new OS thread.
Q40. Which synchronization primitive provides mutual exclusion across threads?
Mutex guards data with a lock for thread-safe access.
Answer: Mutex<T> — provides mutual exclusion for shared data across threads (often used with Arc).
Q41. Which macro is used to define a module-level attribute like crate name?
Inner attributes use #! at crate root.
Answer: #![crate_name] — inner attributes (#![...]) apply to the enclosing crate or module; commonly used in crate root.
Q42. Which keyword imports items from another module or crate?
Use `use` to bring names into scope.
Answer: use — `use std::collections::HashMap;` brings HashMap into scope.
Q43. Which keyword declares a module in Rust source?
Defines a module and its contents.
Answer: mod — `mod utils;` declares a module; `mod name { ... }` defines it inline.
Q44. Which attribute allows conditional compilation for a target OS?
Use cfg attribute with target_os key.
Answer: #[cfg(target_os = "windows")] — enables code only when compiling for Windows; cfg supports many conditional options.
Q45. Which macro is used to include external crates declared in Cargo.toml?
Mostly unnecessary in 2018 edition but still valid.
Answer: extern crate — historically used to link external crates; in the 2018 edition `use` is usually sufficient.
Q46. Which function converts a string slice to an owned String?
Common methods: to_string and String::from.
Answer: to_string() — `let s = "hi".to_string();` or `String::from("hi")` creates an owned String.
Q47. Which method returns an iterator over references to elements of a Vec?
iter() yields &T, iter_mut() yields &mut T.
Answer: iter() — `vec.iter()` returns an iterator over `&T` references; `into_iter()` consumes the Vec.
Q48. Which method consumes an iterator and produces a single accumulated value?
fold takes an initial accumulator and a closure.
Answer: fold() — `iter.fold(init, |acc, x| ...)` reduces an iterator to a single value.
Q49. Which attribute enables deriving Clone and Copy for simple types?
Copyable types are small and have no destructor.
Answer: #[derive(Clone, Copy)] — implements Clone and Copy traits for types that can be bitwise copied.
Q50. Which practice helps avoid panics and handle errors idiomatically in Rust?
Prefer Result and Option handling over panicking in library code.
Answer: Return Result and handle errors explicitly — idiomatic Rust uses Result/Option and explicit error handling rather than widespread panics.
Your Score: 0 / 50
0 Comments