Rust Interview Questions

35 Questions
Rust

Rust

Web DevelopmentIoT

Question 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:

  1. 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;
  2. 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;
  3. Boolean:

    • bool: true or false
    • Example:
      let x: bool = true;
      let y: bool = false;
  4. 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:

  1. 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
  2. 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: () = ();
      }

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.

Recent job openings