What is Rust Standard library ?
The Rust Standard Library is the foundation of portable Rust software, a set of minimal and battle-tested shared abstractions for the broader Rust ecosystem. It offers core types, like Vec<T>
and Option<T>
, library-defined operations on language primitives, standard macros, I/O and multithreading, among many other things.
std
is available to all Rust crates by default. Therefore, the standard library can be accessed in use
statements through the path std
, as in use std::env
.
Multiple choice questions of Rust
Rust (Programming Language)
Q1. Which type cast preserves the mathematical value in all cases?
a. i64 as i32
b. usize as u64
c. i32 as i64
d. f64 as f32
Correct answer is :- i32 as i64
Q2. What do the vertical bars represent here?
str::thread::spawn(|| {
println!(“LinkedIn”);
});
a. a closure
b. a thread
c. a future
d. a block
Correct answer is: a. a closure
Q3. Which choice is not a scalar data type?
a. integer
b. float
c. boolean
d. tuple
Correct answer is :- tuple
Q4. _ cannot be destructured.
a. Traits
b. Tuples
c. Enums
d. Structs
Correct answer is:- Traits
Q5. Which cargo command checks a program for error without creating a binary executable?
a. cargo –version
b. cargo init
c. cargo build
d. cargo check
Correct answer is:- cargo check
Q6. The term box and related phrases such as boxing a value are often used when relating to memory layout. What does box refer to?
a. It’s creating a pointer on the heap that points to a value on the stack.
b. It’s creating a pointer on the stack that points to a value on the heap.
c. It’s creating a memory guard around values to prevent illegal access.
d. It’s an abstraction that refers to ownership. “Boxed” values are clearly labelled.
Correct answer is:- It’s creating a pointer on the stack that points to a value on the heap.
Q7. What is an alternative way of writing slice that produces the same result?
…
let s = String::form(“hello”);
let slice = &s[0..2];
a. let slice = &s[len + 2];
b. let slice = &s[len – 2];
c. let slice = &s.copy(0..2);
d. let slice = &s[..2];
Correct answer is:- let slice = &s[..2];
Q8. Using the ? operator at the end of an expression is equivalent to _.
a. a match pattern that branches into True or False
b. calling ok_error()
c. calling panic!()
d. a match pattern that may result an early return
Correct answer is:- a match pattern that may result an early return
Q9. Which is valid syntax for defining an array of i32 values?
a. Array::with_capacity(10)
b. [i32]
c. Array::new(10)
d. [i32; 10]
Correct answer is:- [i32; 10]
Q10. What syntax is required to take a mutable reference to T, when used within a function argument?
fn increment(i: T) {
// body elided
}
a. *mut T
b. mut ref T
c. mut &T
d. &mut T
Correct answer is :- &mut T
Q11. The smart pointers Rc and Arc provide reference counting. What is the API for incrementing a reference count?
a. .add()
b. .incr()
c. .clone()
d. .increment()
Correct answer is:- .clone()
Q12. What happens when an error occurs that is being handled by the question mark (?) operator?
a. The error is reported and execution continues.
b. An exception is raised. The effect(s) of the exception are defined by the error! macro.
c. The program panics immediately.
d. Rust attempts to convert the error to the local function’s error type and return it as Result::Err. If that fails, the program panics.
Correct answer is :- Rust attempts to convert the error to the local function’s error type and return it as Result::Err. If that fails, the program panics.
Q13. Which comment syntax is not legal?
a. /*
b. #
c. //!
d. //
Correct answer is #
Q14. In matching patterns, values are ignored with .
a. .ignore()
b. an underscore ()
d. .. [answer]
d. skip
Correct answer is .. [answer]
Q15. Defining a _ requires a lifetime parameter.
a. function that ends the lifetime of one of its arguments
b. struct that contains a reference to a value
c. function with a generic argument
d. struct that contains a reference to a boxed value
Correct answer is :- function with a generic argument
Q16. Which example correctly uses std::collections::HashMap’s Entry API to populate counts?
a. use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
let text = “LinkedIn Learning”;
for c in text.chars() {
// Complete this block
}
println!(“{:?}”, counts);
}
b. [ ]
for c in text.chars() {
if let Some(count) = &mut counts.get(&c) {
counts.insert(c, *count + 1);
} else {
counts.insert(c, 1);
};
}
c. [x]
for c in text.chars() {
let count = counts.entry(c).or_insert(0);
*count += 1;
}
d. [ ]
for c in text.chars() {
let count = counts.entry(c);
*count += 1;
}
e. [ ]
for c in text.chars() {
counts.entry(c).or_insert(0).map(|x| x + 1);
}
Correct answer is :- c. [x]
for c in text.chars() {
let count = counts.entry(c).or_insert(0);
*count += 1;
}
Q17. Which fragment does not incur memory allocations while writing to a “file” (represented by a Vec)?
use std::collections::HashMap;
fn main() -> Result<(), Box> {
let mut v = Vec::::new();
let a = "LinkedIn";
let b = 123;
let c = '🧀';
// replace this line
println!("{:?}", v);
Ok(())
}
a. [x]
write!(&mut v, “{}{}{}”, a, b, c)?;
b. [ ]
v.write(a)?;
v.write(b)?;
v.write(c)?;
c. [ ]
v.write(a, b, c)?;
d. [ ]
v.write_all(a.as_bytes())?;
v.write_all(&b.to_string().as_bytes())?;
c.encode_utf8(&mut v);
Correct answer is:- [x]
write!(&mut v, “{}{}{}”, a, b, c)?;
Q18. Does the main function compile? If so, why? If not, what do you need to change?
fn main() {
let Some(x) = some_option_value;
}
a. The code does not compile. let statements require a refutable pattern. Add if before let.
b. The code compiles. let statements sometimes require a refutable pattern.
c. The code does not compile. let statements requires an irrefutable pattern. Add if before let.
d. The code compiles. let do not require a refutable pattern.
Correct answer is:- The code does not compile. let statements requires an irrefutable pattern. Add if before let.
Q19. Which statement about lifetimes is false?
a. Lifetimes were redundantly specified in previous version of Rust.
b. Lifetimes are specified when a struct is holding a reference to a value.
c. Lifetimes are specified when certain values must outlive others.
d. Lifetimes are always inferred by the compiler.
Correct answer is:- Lifetimes are always inferred by the compiler.
Q20. When used as a return type, which Rust type plays a similar role to Python’s None, JavaScript’s null, or the void type in C/C++?
a. !
b. None
c. Null
d. ()
Correct answer is:- ()
Q21. To convert a Result to an Option, which method should you use?
a. .as_option()
b .ok()
c. .to_option()
d. .into()
Correct answer is:- .ok()
Q22. Which statement about the Clone and Copy traits is false?
a. Copy is enabled for primitive, built-in types.
b. Without Copy, Rust applies move semantics to a type’s access.
c. When using Clone, copying data is explicit.
d. Until a type implements either Copy or Clone, its internal data cannot be copied.
Correct answer is:- Copy is enabled for primitive, built-in types.
Q23. Why does this code not compile?
fn returns_closure() -> dyn Fn(i32) -> i32 {
|x| x + 1
}
a. The returned fn pointer and value need to be represented by another trait.
b. Closures are types, so they cannot be returned directly from a function.
c. Closures are types and can be returned only if the concrete trait is implemented.
d. Closures are represented by traits, so they cannot be a return type.
Correct answer is:- Closures are represented by traits, so they cannot be a return type.
Q24. What smart pointer is used to allow multiple ownership of a value in various threads?
a. Arc
b. Box
c. Both Arc and Rc are multithread safe.
d. Rc
Correct answer is:- Arc
Q25. Which types are not allowed within an enum variant’s body?
a. zero-sized types
b. structs
c. trait objects
d. floating-point numbers
Correct answer is:- trait objects
Q26. Which statement about this code is true?
fn main() {
let c = ‘z’;
let heart_eyed_cat = ‘😻’;
}
a. Both are character literals.
d. heart_eyed_cat is an invalid expression.
c. c is a string literal and heart_eyed_cat is a character literal.
d. Both are string literals.
Correct answer is:- Both are character literals.
Q27. Your application requires a single copy of some data type T to be held in memory that can be accessed by multiple threads. What is the thread-safe wrapper type?
a. Mutex>
b. Rc>
c. Arc>
d. Mutex>
Correct answer is:- Arc>
Q28. Which idiom can be used to concatenate the strings a, b, c?
let a = “a”.to_string();
let b = “b”.to_string();
let c = “c”.to_string();
a. String::from(a,b,c)
b. format!(“{}{}{}”, a, b, c)
c. concat(a,b,c)
d. a + b + c
Correct answer is:- format!(“{}{}{}”, a, b, c)
Q29. In this function. what level of access is provided to the variable a?
use std::fmt::Debug;
fn report(a: &T) {
eprintln!(“info: {:?}”, a);
}
a. print
b. read-only
c. read/write
d. debug
Correct answer is:- read-only
Q30. Which choice is not valid loop syntax?
a. loop
b. for
c. while
d. do
Correct answer is:- do
Q31. How do you construct a value of Status that is initialized to Waiting?
enum Status {
Waiting,
Busy,
Error(String),
}
a. let s = Enum::new(Status::Waiting);
b. let s = new Status::Waiting;
c. let s = Status::Waiting;
d. let s = Status::new(Waiting);
Correct answer is:- let s = Status::Waiting;
Q32. Which statement about enums is false?
a. Enums are useful in matching patterns.
b. Option is an enum type.
c. Enum variants can have different types with associated data.
d. the term enum is short for enummap
Correct answer is:- the term enum is short for enummap
Q33. What does an underscore (_) indicate when used as pattern?
a. It matches everything.
b. It matches underscores.
c. It matches any value that has a length of 1.
d. It matches nothing.
Correct answer is:- It matches everything.
Q34. What is a safe operation on a std::cell:UnsafeCell?
a. A &mut T reference is allowed. However it may not cpexists with any other references. and may be created only in single-threaded code.
b. UnsafeCell provides thread-safety. Therefore, creating &T references from multiple threads is safe.
c. The only safe operation is the .get() method, which returns only a raw pointer.
d. Non. UnsafeCell only allows code that would otherwise need unsafe blocks to be written in safe code.
Correct answer is:- The only safe operation is the .get() method, which returns only a raw pointer.
Q35. Generics are useful when you _.
a. need to reduce code duplication by concretizing values and restricting parameters in functions
b. need to reduce code duplication by abstracting values further, such as in function parameters
c. need a supertrait
d. are not sure if you need a specific kind of trait
Correct answer is:- need to reduce code duplication by abstracting values further, such as in function parameters
Q36. How do you create a Rust project on the command-line?
a. cargo new
b. rustup init
c. cargo start
d. rust new-project
Correct answer is:- cargo new
Click here to read our other blogs
Click here to read more Java interview questions and answers