Rust Interview Questions
Rust
Web DevelopmentIoTQuestion 8
What are Rust's primitive types?
Answer:
Rust's primitive types are the basic building blocks of data in the language. These types are built into the language and include scalar types, compound types, and the unit type. Here's an overview of Rust's primitive types:
Scalar Types
Scalar types represent single values. Rust has four primary scalar types:
-
Integers:
- Signed integers:
i8
,i16
,i32
,i64
,i128
,isize
- Unsigned integers:
u8
,u16
,u32
,u64
,u128
,usize
- Example:
let x: i32 = 42; let y: u8 = 255;
- Signed integers:
-
Floating-Point Numbers:
f32
(32-bit floating point)f64
(64-bit floating point, default)- Example:
let x: f32 = 3.14; let y: f64 = 2.71828;
-
Boolean:
bool
:true
orfalse
- Example:
let x: bool = true; let y: bool = false;
-
Character:
char
: Represents a single Unicode scalar value- Example:
let x: char = 'a'; let y: char = '๐';
Compound Types
Compound types can group multiple values into one type. Rust has two primary compound types:
-
Tuples:
- Tuples group multiple values with possibly different types.
- Example:
let tuple: (i32, f64, char) = (42, 3.14, 'a'); let (x, y, z) = tuple; // Destructuring a tuple
-
Arrays:
- Arrays are collections of elements of the same type with a fixed length.
- Example:
let array: [i32; 3] = [1, 2, 3]; let first = array[0]; // Accessing array elements
Unit Type
- Unit Type:
()
- The unit type is a type that has only one value, which is also written
()
. - It is used to indicate the absence of a value or a value that is not significant.
- Functions without a return value implicitly return the unit type.
- Example:
fn main() { let unit: () = (); }
- The unit type is a type that has only one value, which is also written
Summary
Rust's primitive types include scalar types (integers, floating-point numbers, booleans, and characters) and compound types (tuples and arrays), as well as the unit type. These primitive types form the foundation for data representation and manipulation in Rust programs.