Interview Questions on Rust Programming (MCQ)

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

In this article, we have presented the most asked Interview Questions on Rust Programming (MCQ). You must try to answer this to judge your expertise in Rust Programming Language. All questions have been explained with answers.

You can learn some basics of Rust before answering the questions.
Let us get started answering Interview Questions on Rust Programming:

1. Which keyword is used to define a variable in Rust

let
f32
mul
const
let keyword is used to declare a variable in Rust. A sample code statement is like: let pie_variable = 3.14159;

2. Which of the following is immutable by default in Rust but can be made mutable?

variable
const
user defined object
Depends on usage
Variables in Rust are immutable by default but can be made mutable by using the mul keyword.

3. In OOP in Rust, which keyword is used to define Interfaces?

trait
pub
impl
fn
trait keyword is used to define an Interface in Rust. Rust is an Object Oriented Programming Language by default.

Consider this code snippet in Rust:

pub struct AveragedCollection {
    list: Vec<i32>,
    average: f64,
}

4. pub is used to define public in Rust. Are the data members in the structure public or private?

private
public
undefined
depends on function
The struct is defined as public access using the pub keyword in Rust. The data members are private and can be accessed only using the functions of the class. The data is encapsulated within the struct 'object'.

Consider the following Rust code:

pub struct AveragedCollection {
    list: Vec<i32>,
    average: f64,
}

impl AveragedCollection {
    pub fn add(&mut self, value: i32) {
        self.list.push(value);
        self.update_average();
    }
}

5. What is the impl keyword used in Rust?

Implement functionality on types
Define a class
For Inheritance
For Interfaces
impl keyword in Rust is used to implement functionality (functions) on types like structures (defined using struct).

To bring B Tree data structure in scope of the code from the Rust Collections:

use std::collections::BTreeMap;

6. Which code statement in Rust is used to define a BTreeMap object?

let mut btm = BTreeMap::new();
let btm = BTreeMap::new();
BTreeMap btm = std::collections::BTreeMap::new();
BTreeMap btm = BTreeMap.new();
let mut btm = BTreeMap::new(); is the code statement in Rust to define an object for BTreeMap in Rust Collections.

7. Which command is used to compile a Rust code?

rustc code.rs
gcc code.rs
gcrust code.rs
./code
rustc code.rs is the command to compile a Rust code saved in a file named "code.rs".

8. Among const and static in Rust, which one has low memory requirement?

const
static
same for both
depends on datatype
const variables in Rust are dropped and are inlined which allows for several optimizations like constant propagation. static variables are not dropped hence, uses the complete memory required for the variable. Hence, when it is possible to replace static with const, one must do so.

9. Rust is known to be memory safe. Which feature is the main reason for the memory safety of Rust?>

ownership
borrowing
reference
lifetimes
Memory Safety is one of the most important features of Rust which makes it distinct from C++. Ownership is the concept which is the main reason Rust has been able to achieve its memory safety.

10. Arbitrary casting is one of the most dangerous feature of Rust. Which keyword is used for it?

transmute
as
static
(data_type) variable
"transmute" and "as" are keywords for casting. transmute is used for arbitrary casting while "as" is used for safe casting. Arbitrary casting is one of the most dangerous feature of Rust.

Consider the following Rust code snippet:

struct Foo<T: f32> {
    f: T,
}

11. To support Dynamic Sized variables, what should we use in place of "f32"?

?Sized
list all data-types
Use array
Not supported in Rust
Dynamic Sized means the size of data type is not known at run-time. For example, in case of f32, the size is 32 bits so it is not dynamic sized. To enable dynamic sized, we need to use ?Sized.

12. Raw pointers are unsafe pointers in Rust. What is the main use of Raw pointers in Rust?

Foreign Function Interface
C type implementation
Low level memory control
Get address of variables
Raw pointers are considered to be unsafe in Rust. Other types of smart pointers are safe and are covered by compile type checks. In Rust, raw pointers are mainly used for Foreign Function Interface (FFI).

13. In Rust, unsafe function and block allows 3 features. Which one feature is not allowed in Rust "unsafe" ?

turn off the borrow checker
Access or update a static mutable variable
Dereference a raw pointer
Call unsafe functions
unsafe function and block do not allow the code to turn off the borrow checker. 3 special features allowed by unsafe function and block are: Access or update a static mutable variable, Dereference a raw pointer and Call unsafe functions.

Consider this code snippet in Rust:

type Name = String;
let x: Name = "opengenus".to_string();

14. What is the use of "type" keyword in Rust?

alias of another type
dynamic sized datatype
template
User defined data type
"type" keyword in Rust is used to set an alias of another type.

Consider this code snippet in Rust:

struct HasDrop;
impl Drop for HasDrop {
    fn drop(&mut self) {
        println!("Dropping!");
    }
}
fn main() {
    let x = HasDrop;
}

15. What is "Drop" in Rust used for?

Run code when variable is out of scope
Run code as multi-threaded
Run code and drop it if error comes
option4
"Drop" in Rust used to Run code when variable is out of scope.

In C, a marco is defined as follows:

#define FIVE_TIMES(x) 5 * x

In Rust, a macro is defined as follows:

macro_rules! foo {
    () => (let x = 3;);
}

16. In Rust, how is a macro from the above Rust code snippet used?

foo!()
foo
foo(x)
#foo
The macro from the above code is called as foo!(). There are several pre-defined macros like try!, assert!, panic! and many more.

Consider this Rust code snippet:

if true {
    unreachable!();
}

17. What is the predefined macro "unreachable!" in Rust used for?

code should never execute
warning if code not executed
sample code for unexpect path
un-implemented code snippet
The predefined macro "unreachable!" in Rust used to mention code that should never execute.

18. Which library does Rust use for memory allocation?

jemalloc
tcmalloc
ptmalloc
mimalloc
Rust uses jemalloc for memory allocation. Libraries like jemalloc provide efficient implementations of malloc() and calloc() calls and gives a significant performance boost.

19. Who designed Rust from scratch in 2006?

Graydon Hoare
Guido van Rossum
Yukihiro Matsumoto
David Flanagan
Graydon Hoare designed Rust initially in 2006 when he was an employee of Mozilla. The first version was released in 2010 and it was in later years that Rust rose to become a strong Programming Language.

20. What is Cargo in Rust?

Build system and package manager
Build system
Package manager
Collection of Rust libraries
Cargo is a Build system and package manager in Rust.

21. Does Rust guarantee Tail Call Optimization?

No
Yes
Depends on recursion
On using safe block
Rust does not guarantee Tail Call Optimization and is similar to C in this regard.

22. In a function declaration, we can use &self, self and &mul. When is self used?

Value consumed by function
Value mutated by function
Read only reference to value needed
Refer to local variable
In a function declaration, we can use &self, self and &mul. &self is used to pass Read only reference to value while &mul is used to pass a reference to a value which can be modified. self is a base case when a value is pass by value to the function and is consumed / used by the function.

23. When is unwrap() used in Rust?

For debugging
For loop optimizations
To make code linear
Compiler optimizations
In Rust, unwrap() is used for debugging. It is used to handle error by extracting the volume inside a given option.

24. What is the version of the latest Rust release (As of late 2021)?

1.55.0
1.31.1
2.0.0
1.1.0
The version of the latest Rust release in 1.55.0. It was released in September 2021.

25. Which company controls Rust Programming Language?

The Rust Foundation
LLVM
Mozilla
Google
Rust was initially developed and released by Mozilla. In 2020, Mozilla dissolved the team working on Rust due to Covid19 pandemic and this placed the future of Rust to be uncertain. Following this, The Rust Foundation was formed by 5 companies including Mozilla and Google and it is this foundation that currently controls Rust Programming Language.

26. Is Rust an Object Oriented Programming (OOP) Language?

No, it is multi paradigm
No, it is functional
Yes, it is OOP
No, it is Procedural
Rust is a Multi paradigm Programming Language so all designs including OOP can be implemented in Rust.

27. There are many string data types in Rust like Slice, OsStr, str, CStr, Owned, String, OsString and CString. Which one is a primitive data type in Rust?

str
String
Owned
CString
str is the only primitive data type for String in Rust.

28. Does Rust support "Move Constructors"?

No
Yes
Yes, if Move() is implemented
Only for primitive data type
Rust does not support "Move Constructors". It moves value using memcpy.

29. Is Rust Garbage Collected by default?

No
Yes
Depends on memory usage
Only when pointers are used
Rust is not garbage collected by default. One of the key innovations in Rust is to ensure memory safety without the need of garbage collection.

30. How to disable warnings in Rust about unused code segments?

#[allow(dead_code)]
unsafe
safe
#[allow(unused_code)]
To disable warnings in Rust about unused code segments, we need to use the code snippet "#[allow(dead_code)]" in code.

31. How to print data type of a variable in Rust?

std::any::type_name
std::intrinsic::type_name
what_is_this()
variable.type_name()
std::any::type_name::<T> is used to get the data type of a variable in Rust. The documentation of Rust mentions that this function should be used for diagnostic functions only and the results are not guaranteed.

32. How to convert a String to an Integer (int) in Rust?

my_string.parse().unwrap();
my_string.to_int()
int(my_string)
my_string.parse()
my_string.parse().unwrap(); is used to convert a string to an Integer in Rust. Parse() parses a string and hence, can result in an error (err) if the string cannot be parsed as an Integer.

33. There are 3 different ways to return an iterator in Rust: into_itr, itr and itr_mul. What is the yield of the returned iterator for itr?

&T
T
&mut T
mut T
itr will return an iterator which will yield &T. Similarly, itr_mul will yield "&mul T". into_itr can yield 3 values namely T, &T and "&mul T".

34. Rust supports many tools officially like Rustup and Rustfmt. What is Clippy tool in Rust?

Linter
Code formatter
Code cleanup
Code compressor
Clippy is an officially supported tool for Rust which is used as a linter that is a static code analysis tool to check for bugs.

Consider the following Rust code:

fn main() {
    let (.., x, y) = (0, 1, ..);
    print!("{}", b"066"[y][x]);
}

35. What will be the output of the above Rust code?

54
66
Compilation error
Runtime error
The above code snippet in Rust will give the output: 54.
b"006" is of type &'static [u8; 3] with 3 ASCII bytes b0, b6 and b6. b6 in binary is 110. So the resultant data is 0110110 which is the binary representation of 54.
The number can take multiple components with the first two components as y and x. The given code snippet passes 3 components.

Consider the following Rust code snippet:

use std::mem;

fn main() {
    let a;
    let a = a = true;
    print!("{}", mem::size_of_val(&a));
}

36. The above code outputs the size of variable a. What is the output (in bytes)?

0
1
2
4
The output is 0 because the code snippet is an example of zero sized types (ZST) in Rust. The thing is a is overwritten to the expression a = true and expressions are of type () in Rust. () is an example of ZST (zero sized type).

Consider the following Rust code:

fn main() {
    let mut x = 4;
    --x;
    print!("{}{}", --x, --x);
}

37. What is the output of the above code?

44
32
21
undefined
The output is 44 because Rust does not support increment and decrement operators.

Consider the following Rust code:

fn main() {
    let mut a = 5;
    let mut b = 3;
    print!("{}", a-- - --b);
}

38. From previous question, we know increment and decrement operators does not exist in Rust. What will be the output of the above code?

2
option2
option3
option4
Decrement operator -- is parsed as -(-a). So the expression a-- - --b is parsed as a a - (-(-(-(-b)))) resulting in a - b which gives the output as 5 -3 = 2.

39. Which function in Rust helps to clean heap memory?

Drop
flush
clean
deallocate
Drop is used to clean heap memory in Rust.

40. From which code does the compilation of a Rust project begin

carte root
root
cargo root
root use
In a Rust project, "src/main.rs" is the crate root (entry point for a binary crate) and "src/lib.rs" is the entry point for a library crate. Hence, the compilation starts from main.rs in src directory.

41. In a Rust code, what does & denote in a function signature?

type of parameter
Reference of parameter
Address of parameter
Pointer of parameter
In C and C++, & denotes reference. In Rust, when & is used with function signature, & denotes type of parameter.

42. Which operator in Rust is used for namespace?

::
:
.
->
:: in Rust is used for namespace.

43. In Rust, which keyword is used to define a boolean?

bool
boolean
Boolean
::boolean
bool is the keyword to define a boolean variable in Rust.

44. What bracket is used as a placeholder in Rust?

{}
[]
()
::()::
{} is used as a placeholder in Rust.

45. There are two result variants in Rust. What are they?

ok, err
okay, error
success, err
success, fail
ok and err are the two result variants in Rust.

46. Which is the following is a correct Rust syntax?

let slice = &s[0..5];
let slice = s[0..5];
let slice = &s[0->5];
let slice = s[0->5];
let slice = &s[0..5]; is the correct Rust syntax. ".." is used to specify a range in Rust.

With this article at OpenGenus, you must have a strong hold on Rust by answering the above questions. Enjoy and best of luck with your examination / coding interview.

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.